So I have this block of code, which is supposed to figure out how many letters there are in the input. If it is greater than 1 or less than 1(no input), there is an error. However, when running this code, it still prints out "You entered an invalid..." even when I only input in a single letter, which shouldn't be passing through the while loop because its length is only 1. Idk why this is happening any beginner friendly help is appreciated!
letter_guess = input("Enter a single letter to guess: ")
length = len(letter_guess)
while length > 1 or length < 1:
letter_guess = input("You entered an invalid amount of letters, please guess again: ")
You should add length = len(letter_guess) in while loop after the input. As it's not updating currently.
You just need to update the length variable again when you ask for the next guess.
letter_guess = input("Enter a single letter to guess: ")
length = len(letter_guess)
while length > 1 or length < 1:
letter_guess = input("You entered an invalid amount of letters, please guess again: ")
length = len(letter_guess)
Related
I have to build a wordle project. Everything is fine except the fact that whenever past user guesses are printed on the terminal, i get a list out of index error. I have tried adding a word to the list already because I thought the error is happening because of index zero, however it's not working.
Here is my code. Also, ignore the ANSI escape codes.
My code:
import random as random
play_again="Y"
while play_again=="Y":
count=0
list_words=[]
my_file = open("usaWords.txt", "r")
data = my_file.read()
# replacing end splitting the text
# when newline ('\n') is seen.
word_list = data.split("\n")
my_file.close()
#generating a random number
random_word=(random.choice(word_list))
#re-generating a random number if duplicates or if digits less than 3
#converting number into set because they dont allow duplicates
while len((random_word)) !=5:
random_word=(random.choice(word_list))
print('\u001b[47;1m' + '\033[31m'+'Welcome to Wordle! You have six chances to guess the five-letter word. A letter G means you got that letter correct and in the right position. A letter Y means you matched that letter, but it is in the wrong position.A letter B means that letter does not appear in the correct word')
def user_input():
user_guess=input('Please enter your guess: ')
guess_bad=True # Repeating below until the user gives a good input
while guess_bad:
if len(user_guess) !=5: #this should make sure that all digits can be converted to integers!
print('Must contain five letters or more.')
user_guess = input('Please enter a 5-letter word:')
# elif len(set(str(user_guess))) <5:
# print('No duplicates.')
# user_guess = input('Please enter a 5-letter word. No duplicates:')
else:
guess_bad=False
return user_guess
#Docstring required within each function:
"""
Description of function: This function will convert the words into lists to compare and output the answer to user. It also takes in the number of tries and outputs the count.
return: The number of tries.
"""
def add_user_lists(colored_guesses)->int:
background='\u001b[47;1m'
user_guess=user_input()
random_word_list=[]
past_guess=['none']
past_guess.append(user_guess)
user_input_list=[]
for letter in str(random_word):
random_word_list.append(letter)
for letter in str(user_guess):
user_input_list.append(letter)
# Just to check the answers:
print(random_word_list)
print(user_input_list)
#save the colors here
colored_guess=['B','B','B','B','B']
#For storing the old guesses
#This does greens
for i in range (0, len(random_word_list)):
if random_word_list[i]==user_input_list[i]:
colored_guess[i]='G'
elif random_word_list[i] in user_input_list:
colored_guess[i]='Y'
else:
colored_guess[i]='B'
#now you do all of the yellows
colored_guesses.append(colored_guess)
for i in range(len(colored_guesses)):
print(f"{background} Guess {i+1} is {past_guess[i+1]} colors are {''.join(colored_guesses[i])}")
return colored_guesses
colored_guesses=[]
temp=[]
while len(temp)<6 and ['G','G','G','G','G'] not in temp:
temp=add_user_lists(colored_guesses)
if len(temp) >=6:
print("You lost.")
elif ['G','G','G','G','G'] in temp:
print(f'you won! it took {len(temp)} tries!')
play_again=(input("Do you want to play again? Y if yes, N if no: "))
I'm expecting to get responses like:
What is your guess? truck
Guess 1: slice BBBBY
Guess 2: truck BYBBB
What is your guess? delay
Guess 1: slice BBBBY
Guess 2: truck BYBBB
Guess 3: delay BYBYB
What is your guess? wheat
Guess 1: slice BBBBY
Guess 2: truck BYBBB
Guess 3: delay BYBYB
Guess 4: wheat BBYYB
The problem is that colored_guesses is longer then past_guess
So you can't index a non-existing index past_guess[i+1]
You probably want to iterate over past_guess instead.
If you wish to hold the past_guess you should append and not reset it every time.
Here is a small fix:
def add_user_lists(colored_guesses, past_guess)->int:
background='\u001b[47;1m'
user_guess=user_input()
random_word_list=[]
past_guess.append(user_guess)
user_input_list=[]
for letter in str(random_word):
random_word_list.append(letter)
for letter in str(user_guess):
user_input_list.append(letter)
# Just to check the answers:
print(random_word_list)
print(user_input_list)
#save the colors here
colored_guess=['B','B','B','B','B']
#For storing the old guesses
#This does greens
for i in range (0, len(random_word_list)):
if random_word_list[i]==user_input_list[i]:
colored_guess[i]='G'
elif random_word_list[i] in user_input_list:
colored_guess[i]='Y'
else:
colored_guess[i]='B'
#now you do all of the yellows
colored_guesses.append(colored_guess)
for i in range(len(past_guess)):
print(f"{background} Guess {i} is {past_guess[i]} colors are {''.join(colored_guesses[i])}")
return colored_guesses
colored_guesses=[]
temp=[]
past_guess=[]
while len(temp)<6 and ['G','G','G','G','G'] not in temp:
temp=add_user_lists(colored_guesses, past_guess)
if len(temp) >=6:
print("You lost.")
elif ['G','G','G','G','G'] in temp:
print(f'you won! it took {len(temp)} tries!')
play_again=(input("Do you want to play again? Y if yes, N if no: "))
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 months ago.
I am coding a guessing game where the user inputs an integer between 1 and 100 to try and guess the correct number (26). I have to count the number of guesses the user takes to get the correct number. I want to use try and except blocks to allow the user to keep trying until they guess it right.
Right now, my code only allows the user to input one ValueError. I don't want this, I want to keep inputting until I guess the number. Attached is my code. Any help is greatly appreciated!
ex:
I want to input errors ("a", 4.20, "hello") and still have them count as guesses until I guess the number
"a" > 4.20 > "hello" > 26 => Guessed it in 3 tries
def guess(n):
secret_number = 26
if n < secret_number:
return print("Too low!")
elif n > secret_number:
return print("Too high!")
def try_exp():
try:
n = int(input("What is your guess? "))
return n
except ValueError:
n = int(input("Bad input! Try again: "))
return n
def counter():
print("Guess the secret number! Hint: it's an integer between 1 and 100... ")
n = try_exp()
i = 0
while n != 26:
guess(n)
i += 1
n = try_exp()
print(f"You guessed it! It took you {i} guesses.")
counter()
Instead of making try_exp like that, you can use a while loop that will first ask for input, and if the input is valid, then it will break out of the while loop. This is one way to implement it:
def try_exp():
first_input = True
while True:
try:
if first_input:
n = int(input("What is your guess? "))
return n
else:
n = int(input("Bad input! Try again: "))
return n
except ValueError:
first_input = False
In this, we go through an infinite loop, and we have a flag that designates whether it is the first guess or if they have already guessed before. If it is the first guess, we ask them for input, and if it is the second guess, we tell them that they gave incorrect input and ask for more input. After receiving correct input, the function returns n. If the input is incorrect which is when it is not an integer, we set first_input as false. Then, the while loop loops again. It will keep on waiting for input until they submit an integer.
I have to create a program that generates a five digit number which a user has to guess by getting different clues like how many digits they have correct and how many are in the correct position.
The function i have written out now it to find the unique letters aka the letters that each string has in common. Now this works if the length is exactly 5 letters. But i need to have a statement written out (this is too short or long) when the user exceeds a length of 5 or is lower than 5. It says this but counts what is right and adds it to the previous number. This shouldnt be there. Also the numbers shouldnt add only state the right amount in that attempt. Heres it visually:
rannum remove : 24510
enter number: 24511
4
enter number: 12
this is too short
6
heres the code:
while not userguess:
guess = str(input("enter number: "))
if len(guess) < 5:
print("this is too short")
for i in list(set(secretString) & set(guess)):
uniquedigits_found += 1
print(uniquedigits_found)
is there anyway to fix this problem?
You should try resetting your unique digits variable in each iteration of the while loop, and separate the for loop to check matching digits in an else statement:
while not userguess:
uniquedigits_found = 0
guess = str(input("enter number nerd: "))
if len(guess) < 5:
print("this is too short")
elif len(guess) > 5:
print("this is too long")
else:
for i in list(set(secretString) & set(guess)):
uniquedigits_found += 1
print(uniquedigits_found)
I am trying to design a hungman game using simple while loop and if else statement.
Rules of the game:
1.Random word is selected from a list of words
2.User is informed when the word is selected and asked to provide his/ her first guess
3.If the user's guess is correct, the letter is console and inform the user how many letters left
The user will get only 5 lives to play the game.
1.import random
2.import string
3.def hungman():
4.words = ["dog", "monkey", "key", "money", "honey"]
5.used_letters = []
6.word = words[random.randrange(len(words))]
7.lives=5
8.while len(word) > 0 and lives > 0:
9.guess = input("Please guess the letter: ")
10.if 'guess' in word:
11.print(guess, " is a correct guess")
12.used_letters.appened(guess)
13.if used_letters.len == word.len:
14.print("Congratulation, You have guessed the correct letter: ",word)
15.else:
16.remaining_letters = word.len - used_letters.len
17.print("You have", remaining_letters, "left")
18.else:
19.lives = lives - 1
20.if lives == 0:
21.print("Sorry! you don't have more lives to continue the game")
22.print("Correct word is: ", word)
23.break
24.else:
25.print("You have", lives , " left")
26.hungman()
The program should ask for the user input which will store in guess variable. If the letter given by the user is one of the letters of word string then the code prompts that the given input is correct and append the letter in the used_letters list. Else it shows the length of the remaining letters for wrong user input. Additionally, if the user fails to guess the letter correctly he or she will lose 1 life as well.
However, as per my code after the while loop in line number 8 the control goes to line no. 18 although I provided correct letter as user input. Line 10 to 17 totally discarded. I could not find the reason of this nature.
Please help me in this regard.
Thank you
You have a couple of issues in your code.
The one you mentioned is because of quotation marks in line 10. Should be
if guess in word:
in line 12 you have a typo
used_letters.append(guess)
to get the length of a list you should use function len(), e.g.
if len(used_letters) == len(word)
And finally you have an issue with exiting the loop in case of the correct answer. You should use
while len(word) > len(used_letters) and lives > 0:
This question already has an answer here:
Python "if" statement not working
(1 answer)
Closed 4 years ago.
I'm learning Python for fun at the moment, and it went all well until now. I'm trying to extend the "Guess the Word"-Game, for example being able to let the Player choose a Word by himself (when 2 People play, 1 chooses the Word, the other guesses) I bet that my Mistake is obvious to me as soon as you point it out, but I'm gonna ask anyway. Well, here is the Code. I put in the entire Program, even tough only the top part should matter. I just put in the rest because it isn't much and maybe you guys can understand it better then.
print("Do you wish to set the Word yourself, or let the program choose?")
user_input = input("1 for own Input - 0 for Program-Input")
if user_input == 1:
Keyword = input("Type in the Word you want to use!")
else:
Keyword = "castle"
word = list(Keyword)
length = len(word)
right = list ("_" * length)
used_letters = list()
finished = False
while finished == False:
guess = input("Guess a Letter!")
if guess not in Keyword:
print("This letter is not in the word. Sorry...")
for letter in word:
if letter == guess:
index = word.index(guess)
right[index] = guess
word[index] = "_"
if guess in used_letters[0:100]:
print("You already used that letter before!")
else:
used_letters.append(guess)
list.sort(used_letters)
print(right)
print("Used letters:")
print(used_letters)
if list(Keyword) == right:
print("You win!")
finished = True
input('Press ENTER to exit')
My problem is, I wanna add the Function to be able to choose if you want to set a Word yourself, or use the word the Program has, defined as "Keyword". But no matter what I input, it always starts with "Guess a Letter" instead of skipping down to where the program sets the Keyword. Thank you in advance for your answers! :)
There's 2 issues with your code.
You put the entire block of code into the else statement. This means that if the if user_input == 1: block ever executed, you would only ask your user for a word and then the program would end because the else statement would be skipped.
You are using if user_input == 1: as your check and this will never be true because user inputs are always read in as strings. A string 1 will never equal the integer 1. This is why your program always skips to the else statement. You need to do if int(user_input) == 1:
Whenever you collect a user's input using the input function, it is a string, not int. this means you will have to either parse the value into an int or evaluate it with a string.
option 1: parsing to int:
user_input = int(input("1 for own Input - 0 for Program-Input"))
option 2: evaluating with string:
if user_input == "1":
input returns a string not a integer so it can never be equal to 1 instead it will be equal to "1".
Plus the code for the user guessing only runs when the program chooses the word so it needs to be unindented.
As a side note your code currently registered capital letters as being different from lower case, you can fix this by putting a .lower() after each input which will turn all capital letters into lowercase.
print("Do you wish to set the Word yourself, or let the program choose?: ")
user_input = input("1 for own Input - 0 for Program-Input")
if user_input == "1":
Keyword = input("Type in the Word you want to use: ").lower()
else:
Keyword = "castle"
word = list(Keyword)
length = len(word)
right = list ("_" * length)
used_letters = list()
finished = False
while finished == False:
guess = input("Guess a Letter: ").lower()
if guess not in Keyword:
print("This letter is not in the word. Sorry...")
for letter in word:
if letter == guess:
index = word.index(guess)
right[index] = guess
word[index] = "_"
if guess in used_letters[0:100]:
print("You already used that letter before!")
else:
used_letters.append(guess)
list.sort(used_letters)
print(right)
print("Used letters:")
print(used_letters)
if list(Keyword) == right:
print("You win!")
finished = True
input('Press ENTER to exit')