I tried to make a simple version of the hangman game. But when I run it, I can't add the letters in order.
The 'count' variable may be the problem. Any can help me ?
Thank you! :)
word = 'houses'# <--just for testing
word = list(word)
print(word)
p2 = ' __ ' * len(word)
p2 = p2.split()
print(p2)
lives = len(word)
print("lives: ", lives)
count = 0
while word != p2:
letter = input("enter a letter: ")
if letter in word:
for x in word:
if x == letter:
p2[count] = letter
#print("cont: ", count)
else:
continue
count+=1
print("p2: ",p2)
else:
lives -= 1
print("You have {} lives left".format(lives))
if lives == 0:
break
Well i wasn't able to understand your point of view about the Hangman but following code is the optimized form of your code and also the my playing interpretation of this game e.g. how this should be played
word = 'houses'# <--just for testing
word = list(word)
print(word)
p2 = ' __ ' * len(word)
p2 = p2.split()
print(p2)
lives = len(word)
print("lives: ", lives)
while word != p2:
letter = input("enter a letter: ")
if letter in word and letter not in p2:
locations = [i for i, x in enumerate(word) if x == letter ]
for location in locations:
p2[location] = letter
print("p2: ",p2)
else:
lives -= 1
print("You have {} lives left".format(lives))
if lives == 0:
break
print('You LOST' if lives == 0 else 'You WON')
Screenshot of the Both Executions of the game (Win & Loss)
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 see the point of the question stays in the first elif:
import random as rnd
vowels="aeiou"
consonants="bcdfghlmnpqrstvz"
alphabet=vowels+consonants
vocabulary={}
index=0
word=""
positions=[]
while index<5:
random_lenght=rnd.randint(2,5)
while len(word)<random_lenght:
random_letter=rnd.randint(0,len(alphabet)-1)
if len(word)==0:
word+=alphabet[random_letter]
elif random_letter != positions[-1] and len(word)>0:
if word[-1] not in vowels:
word+=alphabet[random_letter]
if word[-1] not in consonants:
word+=alphabet[random_letter]
elif random_letter == positions[-1]:
break
if random_letter not in positions:
positions.append(random_letter)
if word not in vocabulary:
vocabulary[index]=word
index+=1
word=""
The result doesn't satisfy me as you suppose:
{0: 'in', 1: 'th', 2: 'cuu', 3: 'th', 4: 'vd'}
Any help would be appreciated.
What you want should be something like this (based on your implementation) :
import random as rnd
vowels="aeiou"
consonants="bcdfghlmnpqrstvz"
alphabet=vowels+consonants
vocabulary={}
index=0
word=""
positions=[]
while index<5:
random_lenght=rnd.randint(2,5)
while len(word)<random_lenght:
random_letter=rnd.randint(0,len(alphabet)-1)
if len(word) == 0:
word+=alphabet[random_letter]
elif random_letter != positions[-1] and len(word)>0:
if word[-1] not in vowels and alphabet[random_letter] not in consonants:
word+=alphabet[random_letter]
elif word[-1] not in consonants and alphabet[random_letter] not in vowels:
word+=alphabet[random_letter]
if random_letter not in positions:
positions.append(random_letter)
if word not in vocabulary:
vocabulary[index]=word
index+=1
word=""
And another version :
import string
import random
isVowel = lambda letter: letter in "aeiou"
def generateWord(lengthMin, lengthMax):
word = ""
wordLength = random.randint(lengthMin, lengthMax)
while len(word) != wordLength:
letter = string.ascii_lowercase[random.randint(0,25)]
if len(word) == 0 or isVowel(word[-1]) != isVowel(letter):
word = word + letter
return word
for i in range(0, 5):
print(generateWord(2, 5))
So I'm writing a hangman program and I'm having trouble getting the current guesses to display as underscores with the correct letters guessed replacing an underscore. I can get the function to work once (thats the insert_letter function) and I know its just replacing every time it goes through the loop, but I can't return the new current without quitting the loop so if someone could offer another way to get the guesses to keep updating that would be great!
def insert_letter(letter, current, word):
current = "_" * len(word)
for i in range (len(word)):
if letter in word[i]:
current = current[:i] + letter + current[i+1:]
return current
def play_hangman(filename, incorrect):
words = read_words(filename)
secret_word = random.choice(words)
num_guess = 0
letters_guessed = set()
letter = input("Please enter a letter: ")
while num_guess < incorrect:
letter = input()
if letter in secret_word:
current = insert_letter(letter, current, secret_word)
print(current)
else:
num_guess += 1
current = "_" * len(secret_word)
print(current)
letters_guessed.add(letter)
You didn't show the code for your insert_letter() function so I wrote an alternative -- display_remaining(). Give this a try:
import random, sys
def play_hangman(filename, incorrect):
words = read_words(filename)
secret_word = random.choice(words)
num_guess = 0
letters_guessed = set()
while num_guess < incorrect:
letter = input("Please enter a letter: ")
letters_guessed.add(letter)
current = display_remaining(secret_word, letters_guessed)
print(current)
if not letter in secret_word:
print("Incorrect guess.")
num_guess += 1
if not '_' in current:
print("Congratulations! You've won!")
sys.exit(0)
print("Sorry. You've run out of guesses. Game over.")
def display_remaining(word, guessed):
replaced = word[:]
for letter in word:
if (not letter == '_') and letter not in guessed:
replaced = replaced.replace(letter, '_', 1)
return replaced
def read_words(filename):
with open(filename, 'rU') as f:
return [line.strip() for line in f]
if __name__ == '__main__':
play_hangman('words.txt', 6)
NOTE: With this implementation, your words file shouldn't have any words containing the underscore character.