I am trying to create a program that asks for a word input until '' is entered. Then the program will print out all of the words joined in a sentence. Then take the first letter of each word to make an acrostic. I am using python. Example shown below. Thank you in advance. This is due really soon. :)
What I have coded:
sentence = []
acrostic = []
word = -1
while word:
sentence.append(word)
acrostic.append(sentence[0].upper())
print(sentence)
print("-- {}".format(acrostic))
What I want the code to do:
Word: A
Word: cross
Word: tick
Word: is
Word: very
Word: evil
Word:
A cross tick is very evil
-- ACTIVE
For input:
in a loop, ask the user a word, if it nothing just stop
if it's a word, save it in sentence and it's first letter in acrostic (word[0] not sentence[0])
For output:
for the sentence join the words with a space : " ".join(sentence)
for the acrostic, join the letters with nothing : "".join(acrostic)
sentence = []
acrostic = []
while True:
word = input('Please enter a word, or enter to stop : ')
if not word:
break
sentence.append(word)
acrostic.append(word[0].upper())
print(" ".join(sentence))
print("-- {}".format("".join(acrostic)))
Gives
Please enter a word, or " to stop : A
Please enter a word, or " to stop : cross
Please enter a word, or " to stop : tick
Please enter a word, or " to stop : is
Please enter a word, or " to stop : very
Please enter a word, or " to stop : evil
Please enter a word, or " to stop :
A cross tick is very evil
-- ACTIVE
python 3.8 or later
sentence = []
acrostic = []
while user_input := input('word: '):
sentence.append(user_input)
acrostic.append(user_input[0].upper())
print(' '.join(sentence))
print(f"-- {''.join(acrostic)}")
output:
word: A
word: cross
word: tick
word: is
word: very
word: evil
word:
A cross tick is very evil
-- ACTIVE
python 3.6 and 3.7
sentence = []
acrostic = []
while True:
user_input = input('word: ')
if not user_input:
break
sentence.append(user_input)
acrostic.append(user_input[0].upper())
print(' '.join(sentence))
print(f"-- {''.join(acrostic)}")
python 3.5 or earlier
sentence = []
acrostic = []
while True:
user_input = input('word: ')
if not user_input:
break
sentence.append(user_input)
acrostic.append(user_input[0].upper())
print(' '.join(sentence))
print('-- {}'.format(''.join(acrostic)))
Maybe you're looking for something like this:
sentence = []
acrostic = []
word = -1
while word != "":
word = input("Word: ")
if word:
sentence.append(word)
acrostic.append(word[0].upper())
print(" ".join(sentence))
print("-- {}".format("".join(acrostic)))
Goal: To extract first letter of each word untill '' is entered.
acrostic = ""
sentence = ""
while(True):
word = input("enter a word= ")
if(word!=''):
acrostic+=word[0].upper()
sentence+=word+" "
else:
break
print(sentence)
print(acrostic)
With your sample input;
enter a word= A
enter a word= cross
enter a word= tick
enter a word= is
enter a word= very
enter a word= evil
enter a word=
output
A cross tick is very evil
ACTIVE
While everybody has you covered for basic loops, this is a nice example to use the iter(callable, sentinel) pattern:
def initial():
return input('Word: ')[:1]
print('-- ' + ''.join(iter(initial, '')))
Will produce:
Word: A
Word: cross
Word: tick
Word: is
Word: very
Word: evil
Word:
-- Active
Related
So basically I'm trying to make a hangman game, and my code works fine but I'm getting confused with the end=" "
print("Welcome to hangman game!")
import random
words = ["facts", "air", "count", "wack"]
word = random.choice(words)
letters_guessed = []
guesses_left = 9
list(word)
while guesses_left > 0:
print("The word contains {} letters".format(len(word)))
for i in word:
print("_", end=" ")
user = input("Enter a letter --> ")
This is the output I get:
Welcome to hangman game!
The word contains 3 letters
_ _ _ Enter a letter -->
I want to print "Enter a letter --> " below the "_ _ _".
How can I do that? This is my first time using end=" " so yeah
In that case, you need to use an empty print() after the for loop:
for i in word:
print("_", end=" ")
print()
Or simply, use sep. Also, you need to have 2 arguments for sep:
print("_"*len(word), sep=" ")
You could add a \n to your input prompt:
user = input("\nEnter a letter --> ")
print("Welcome to hangman game!")
import random
words = ["facts", "air", "count", "wack"]
word = random.choice(words)
letters_guessed = []
guesses_left = 9
list(word)
while guesses_left > 0:
print("The word contains {} letters".format(len(word)))
for i in word:
print("_", end=" ")
user = input("Enter a letter : ")
It is more good looking
Good evening everyone..... i wrote a vowel eater program with the code below
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
userWord = userWord.upper()
for letter in userWord:
if letter == 'A':
continue
elif letter == 'E':
continue
elif letter == 'I':
continue
elif letter == 'O':
continue
elif letter == 'U':
continue
else:
print(letter)
It run fine but i want to use concatenation operation to ask python to combine selected letters into a longer string during subsequent loop turns, and assign it to the wordWithoutVowels variable.....
I really appreciate any help or suggestions thanks in advance
is this what you need?
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
userWord = userWord.upper()
for letter in userWord:
if letter == 'A':
word = letter
continue
elif letter == 'E':
continue
elif letter == 'I':
continue
elif letter == 'O':
continue
elif letter == 'U':
continue
else:
wordWithoutVowels+=letter
print(wordWithoutVowels)
Another approach. You can prepare a set of vowels you want to filter-out before-hand and then use str.join() to obtain you string:
userWord = input("Please Enter a word: ")
vowels = set('aeiou')
wordWithoutVowels = ''.join(character for character in userWord if not character.lower() in vowels)
print(wordWithoutVowels)
Prints (for example):
Please Enter a word: Hello World
Hll Wrld
I'm sorry I didn't read the original post (OP) more carefully. Poster clearly asked for a way to do this by concatenation in a loop. So instead of excluding vowels, we want to include the good characters. Or instead of looking for membership, we can look for not in membership.
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
vowels = 'aAeEiIoOuU'
wordWithoutVowels = '' # initialize to empty string
for letter in userWord:
if letter not in vowels:
wordWithoutVowels += letter # equivalent to wordWithoutVowels = wordWithoutVowels + letter
print(wordWithoutVowels)
Please Enter a word: Hello World
Hll Wrld
or you can try this:
wordWithoutVowels = ""
user = input("Enter a word: ")
userWord = user.upper()
for letter in userWord:
if letter == "A":
continue
elif letter == "E":
continue
elif letter == "O":
continue
elif letter == "I":
continue
elif letter == "U":
continue
else:
wordWithoutVowels += letter
print(wordWithoutVowels)
Using str.replace() seems like a natural way to go for a problem like this
Brute Force
Just go through all of the vowels. And if they exist in input string, replace them
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
userWord = userWord.upper()
# make a copy of userWord
output = userWord
# replace vowels
output = output.replace('A', '') # replace A with empty string
output = output.replace('E', '') # replace E with empty string
output = output.replace('I', '') # replace I with empty string
output = output.replace('O', '') # replace O with empty string
output = output.replace('U', '') # replace U with empty string
print(output)
Please Enter a word: Hello World
HLL WRLD
Use a loop
This is a little more elegant. And you won't have to convert the input to uppercase.
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
# make a copy of userWord
output = userWord
# replace vowels
vowels = 'aAeEiIoOuU'
for letter in vowels:
output = output.replace(letter, '') # replace letter with empty string
print(output)
Please Enter a word: Hello World
Hll Wrld
Try this. I think it's the easiest way:
word_without_vowels = ""
user_word = input("Enter a word")
user_word = user_word.upper()
for letter in user_word:
# Complete the body of the loop.
if letter in ("A","E","I","O","U"):
continue
word_without_vowels+=letter
print(word_without_vowels)
user_word =str(input("Enter a Word"))
# and assign it to the user_word variable.
user_word = user_word.upper()
vowels = ('A','E','E','I','O','U')
for letter in user_word:
if letter in vowels:
continue
elif letter == vowels:
letter = letter - vowels
else:
print(letter)
A one liner that does what you need is:
wordWithoutVowels = ''.join([ x for x in userWord if x not in 'aeiou'])
or the equivalent:
wordWithoutVowels = ''.join(filter(lambda x : x not in 'aeiou', userWord))
The code is creating a list containing the letters in the string that are not vowels and then joining them into a new string.
You just need to figure out how to handle the lower/capital cases. You could do x.lower() not in 'aeiou', check if x is in 'aeiouAEIOU', ... you have plenty of choices.
user_word = input('enter a word:')
user_word = user_word.upper()
for letter in user_word:
if letter in ('A','E','I','O','U'):
continue
print(letter)
word_without_vowels = ""
vowels = 'A', 'E', 'I', 'O', 'U'
user_word = input('enter a word:')
user_word = user_word.upper()
for letter in user_word:
if letter in vowels:
continue
word_without_vowels += letter
print(word_without_vowels)
I am trying to add the character value of the ord function, from a user input. I am able to get it to print out the value of each letter but I am stuck on adding up the entire value for the word the user inputs.
Here is what I have so far:
def main():
key_word = "quit"
word = ""
while word != key_word:
word = input(str("Enter a word: "))
word = word.lower()
for letter in word:
value = ord(letter)
character = value - 96
print(character)
if word == key_word:
print(end="")
main()
Are you asking for the sum of the ord values?
If so:
key_word = "quit"
word = ""
total = 0
while word != key_word:
word = input(str("Enter a word: "))
word = word.lower()
for letter in word:
value = ord(letter)
total += ord(letter)
character = value - 96
print(character)
if word == key_word:
print(end="")
print(total)
You want adds up the value of each letter of the word :
while word != key_word:
word = input(str("Enter a word: "))
word = word.lower()
word_value = 0
for letter in word:
value = ord(letter)
character = value - 96
word_value += character
print(character)
print('Total word value', word_value)
if word == key_word:
print(end="")
I am trying to expand on Codeacademy's Pig Latin converter to practice basic programming concepts.
I believe I have the logic nearly right (I'm sure it's not as concise as it could be!) and now I am trying to output the converted Pig Latin sentence entered by the user on a single line.
If I print from inside the for loop it prints on new lines each time. If I print from outside it only prints the first word as it is not iterating through all the words.
Could you please advise where I am going wrong?
Many, many thanks for your help.
pyg = 'ay'
print ("Welcome to Matt's Pig Latin Converter!")
def convert(original):
while True:
if len(original) > 0 and (original.isalpha() or " " in original):
print "You entered \"%s\"." % original
split_list = original.split()
for word in split_list:
first = word[0]
new_sentence = word[1:] + first + pyg
final_sentence = "".join(new_sentence)
print final_sentence
break
else:
print ("That's not a valid input. Please try again.")
return convert(raw_input("Please enter a word: "))
convert(raw_input("Please enter a word: "))
Try:
pyg = 'ay'
print ("Welcome to Matt's Pig Latin Converter!")
def convert(original):
while True:
if len(original) > 0 and (original.isalpha() or " " in original):
final_sentence = ""
print "You entered \"%s\"." % original
split_list = original.split()
for word in split_list:
first = word[0]
new_sentence = word[1:] + first + pyg
final_sentence = final_sentence.append(new_sentence)
print final_sentence
break
else:
print ("That's not a valid input. Please try again.")
return convert(raw_input("Please enter a word: "))
convert(raw_input("Please enter a word: "))
It's because you are remaking final_sentence every time in the for loop instead of adding to it.
I'm not sure of the program logic but a quick solution would be appending all the final_sentence in a list, and after the for print the list with a Join.
pyg = 'ay'
print ("Welcome to Matt's Pig Latin Converter!")
def convert(original):
to_print = []
while True:
if len(original) > 0 and (original.isalpha() or " " in original):
print "You entered \"%s\"." % original
split_list = original.split()
for word in split_list:
first = word[0]
new_sentence = word[1:] + first + pyg
final_sentence = "".join(new_sentence)
to_print.append(final_sentence)
print " ".join(to_print)
break
else:
print ("That's not a valid input. Please try again.")
return convert(raw_input("Please enter a word: "))
convert(raw_input("Please enter a word: "))
This code does what you want?
Your issue is here:
for word in split_list:
first = word[0]
new_sentence = word[1:] + first + pyg
final_sentence = "".join(new_sentence)
print final_sentence
You are joining a single word to itself. You will want to save all the words from inside the loop, then print them once the loop are processed them all.
final = []
for word in split_list:
new_word = word[1:] + word[0] + pyg
final.append(new_word)
print ' '.join(final)
Or, just for fun, here's the one-liner:
print ' '.join([word[1:]+word[0]+'ay' for word in split_list])
EDIT: Also, #furas makes a good point in their comment, to print with no newline simply add a , to the end of the print statement:
for word in split_list:
first = word[0]
print word[1:] + first + pyg,
For an assignment I need to write a basic HANGMAN game. It all works except this part of it...
The game is supposed to print one of these an underscore ("_") for every letter that there is in the mystery word; and then as the user guesses (correct) letters, they will be put in.
E.G
Assuming the word was "word"
User guesses "W"
W _ _ _
User guesses "D"
W _ _ D
However, in many cases some underscores will go missing once the user has made a few guesses so it will end up looking like:
W _ D
instead of:
W _ _ D
I can't work out which part of my code is making this happen. Any help would be appreciated! Cheers!
Here is my code:
import random
choice = None
list = ["HANGMAN", "ASSIGNEMENT", "PYTHON", "SCHOOL", "PROGRAMMING", "CODING", "CHALLENGE"]
while choice != "0":
print('''
******************
Welcome to Hangman
******************
Please select a menu option:
0 - Exit
1 - Enter a new list of words
2 - Play Game
''')
choice= input("Enter you choice: ")
if choice == "0":
print("Exiting the program...")
elif choice =="1":
list = []
x = 0
while x != 5:
word = str(input("Enter a new word to put in the list: "))
list.append(word)
word = word.upper()
x += 1
elif choice == "2":
word = random.choice(list)
word = word.upper()
hidden_word = " _ " * len(word)
lives = 6
guessed = []
while lives != 0 and hidden_word != word:
print("\n******************************")
print("The word is")
print(hidden_word)
print("\nThere are", len(word), "letters in this word")
print("So far the letters you have guessed are: ")
print(' '.join(guessed))
print("\n You have", lives,"lives remaining")
guess = input("\n Guess a letter: \n")
guess = guess.upper()
if len(guess) > 1:
guess = input("\n You can only guess one letter at a time!\n Try again: ")
guess = guess.upper()
while guess in guessed:
print("\n You have already guessed that letter!")
guess = input("\n Please take another guess: ")
guess = guess.upper()
guessed.append(guess)
if guess in word:
print("*******************************")
print("Well done!", guess.upper(),"is in the word")
word_so_far = ""
for i in range (len(word)):
if guess == str(word[i]):
word_so_far += guess
else:
word_so_far += hidden_word[i]
hidden_word = word_so_far
else:
print("************************")
print("Sorry, but", guess, "is not in the word")
lives -= 1
if lives == 0:
print("GAME OVER! You ahve no lives left")
else:
print("\n CONGRATULATIONS! You have guessed the word")
print("The word was", word)
print("\nThank you for playing Hangman")
else:
choice = input("\n That is not a valid option! Please try again!\n Choice: ")
You have hidden_word = " _ " * len(word)
This means that at start for a two letter word, you have [space][underscore][space][space][underscore][space].
When you then do word_so_far += hidden_word[i], for i = 0, you will append a space, not an underscore.
The quickest fix would seem to be:
Set hidden_word to just be _'s (hidden_word = " _ " * len(word))
When you print out the word, do
hidden_word.replace("_"," _ ") to add the spaces around the underscores back
#Foon has showed you the problem with your solution.
If you can divide your code up into small functional blocks, it makes it easier to concentrate on that one task and it makes it easier to test. When you are having a problem with a specific task it helps to isolate the problem by making it into a function.
Something like this.
word = '12345'
guesses = ['1', '5', '9', '0']
def hidden_word(word, guesses):
hidden = ''
for character in word:
hidden += character if character in guesses else ' _ '
return hidden
print(hidden_word(word, guesses))
guesses.append('3')
print(hidden_word(word, guesses))
Below code solves the problem.you can do some modifications based on your requirement.If the Guessed letter exists in the word.Then the letter will be added to the display variable.If not you can give a warning .But note that it might tempt you to write ELSE statement inside the for loop(condition:if guess not in word).If you do like that then the object inside the Else statement will be repeated untill the For loop stops.so that's why it's better to use a separete IF statement outside the for loop.
word="banana"
display=[]
for i in word:
display+="_"
print(display)
while True:
Guess=input("Enter the letter:")
for position in range(len(word)):
if Guess==word[position]:
display[position]=word[position]
print(display)
if Guess not in word:
print("letter Doesn't exist")