Crashing when improper input given more than once - python

I'm trying to make a simple number guesser program, it works pretty well however if I enter 'a' twice instead of a valid int it crashes out. Can someone explain what I'm doing wrong here.
import random
def input_sanitiser():
guess = input("Please enter a number between 1 and 10: ")
while True:
if type(guess) != int:
guess = int(input("That isn't a number, try again: "))
elif guess not in range (1,11):
guess = int(input("This is not a valid number, try again: "))
else:
break
def main():
number = random.randrange(1,10)
guess = 0
input_sanitiser()
while guess != number:
if guess < number:
print("This number is too low!")
input_sanitiser()
if guess > number:
print("This number is too high!")
input_sanitiser()
else:
break
print ("Congratulations, you've guessed correctly")
if __name__ == "__main__":
main()

You want to check the input before trying to convert it to int:
int(input("This is not a valid number, try again: "))
I would write:
while True:
try:
guess = int(input("This is not a valid number, try again: "))
except ValueError:
pass
else:
break
Side note: the code isn't working as expected:
def main():
number = random.randrange(1,10)
guess = 0
input_sanitiser() # <<<<<<<<<<
while guess != number:
Note that input_sanitiser does not modify the variable guess in main, you need some other way round, like processing the input then returning the result from input_sanitiser, like this:
def input_sanitiser():
guess = input("Please enter a number between 1 and 10: ")
while True:
try:
guess = int(input("This is not a valid number, try again: "))
except ValueError:
continue # keep asking for a valid number
if guess not in range(1, 11):
print("number out of range")
continue
break
return guess
def main():
number = random.randrange(1,10)
guess = input_sanitiser()
while guess != number:
if guess < number:
print("This number is too low!")
guess = input_sanitiser()
if guess > number:
print("This number is too high!")
guess = input_sanitiser()
else:
break
print ("Congratulations, you've guessed correctly")

Related

Getting error from implementing Try/Except

I am trying to add a try/except to my guessing game for non numerical entries from the user. Im not really sure how to implement it with my code but I did try but got an error saying:
ValueError: invalid literal for int() with base 10: 'v'
I am not sure how to rearrange my code to get it to work with the try/except.
def guessing_game(secret_number: int, user_guess: int):
num_tries: int = 0
user_name: str = input("Please enter your name: ")
print(f"Hello {user_name}, i am thinking of a number between 1 and 20")
secret_number: int = randint(1, 19)
user_guess: int = int(input("Guess what it is: "))
try:
while num_tries != 5:
if user_guess > secret_number:
user_guess = int(input("Your guess is too high. Try again: "))
elif user_guess < secret_number:
user_guess = int(input("Your guess is too low. Try again: "))
else:
print(f"Congrats {user_name}, {secret_number} was the number i was thinking of")
break
num_tries += 1
if user_guess != secret_number and num_tries == 5:
print(f"Sorry.The number I was thinking of was {secret_number}")
except ValueError:
print("Error, value must be numerical")
guessing_game(2, 8)
You're probably looking for something like this. No need to wrap everything in a function here (you weren't using the two arguments you passed in anyway).
The outer for loop handles stopping the game once all attempts are exhausted; Python's (quite unique) for/else structure handles losing the game.
The inner while loop loops for as long as the user is giving invalid input; you could add if not (1 <= user_guess <= 19): raise ValueError() in there to also have validation for whether the user is being silly and entering e.g. -1 or 69.
To simplify things, there's only one input() any more, and the game loop modifies the prompt for it.
from random import randint
user_name: str = input("Please enter your name: ")
print(f"Hello {user_name}, i am thinking of a number between 1 and 20")
secret_number: int = randint(1, 19)
prompt = "Guess what it is: "
for num_tries in range(5):
while True:
try:
user_guess: int = int(input(prompt))
break # out of the while
except ValueError:
print("Error, value must be numerical")
if user_guess > secret_number:
prompt = "Your guess is too high. Try again: "
elif user_guess < secret_number:
prompt = "Your guess is too low. Try again: "
else:
print(f"Congrats {user_name}, {secret_number} was the number i was thinking of")
break
else: # for loop was not `break`ed out of
print(f"Sorry. The number I was thinking of was {secret_number}")
Error explanation:
You are not correctly catching the exception because the input casting is outside the try block.
When user tries to enter a literal string, the line:
user_guess: int = int(input("Guess what it is: "))
raises ValueError because that string is not int-castable and the instruction is not inside the try, meaning that the default traceback handles the exception.
Just move that line inside the try block
try:
user_guess: int = int(input("Guess what it is: "))
Code improvement:
That been said, you need to organize your code better. First off your function should just do the matching between user input and secret number. Then you would create the loop and call that function for each user input:
def guessing_game(secret_number: int, user_guess: int):
if user_guess > secret_number:
print("Your guess is too high.")
elif user_guess < secret_number:
user_guess = print("Your guess is too low.")
else:
print(f"Congrats {user_name}, {secret_number} was the number i was thinking of")
return True
user_name = input("Please enter your name: ") # String casting is redundant here.
print(f"Hello {user_name}, i am thinking of a number between 1 and 20")
secret_number = randint(1, 19) # Why not (1,20) though?
# Here is the loop. It keeps prompting the user to enter a number and if the
# input represents a valid integer the function is called to compair them.
num_tries = 0
while True:
if num_tries == 5:
print(f"Sorry.The number I was thinking of was {secret_number}")
break
try:
user_guess = int(input("Guess what it is: "))
if guessing_game(secret_number, user_guess) == True:
break
except ValueError:
print("Error, value must be numerical")
num_tries += 1

How to create a loop within this game successfully?

I'm fairly new to Python so I'm not sure how to go about this. I have created this random number guessing game, and I have it down except for the fact that the game is supposed to never end. Once the user guesses the number, the game should start over. Here is my code.
import random
num = random.randint(1, 100)
def main():
guess_num = 0
guess = int(input("Enter an integer from 1 to 100: "))
while num != guess:
if guess < num:
print("Too low, try again.")
guess = int(input("Enter an integer from 1 to 100: "))
guess_num+=1
elif guess > num:
print("Too high, try again.")
guess = int(input("Enter an integer from 1 to 100: "))
guess_num+=1
else:
print("Congratulations, that's correct!")
guess_num = guess_num+1
print("You guessed "+str(guess_num)+" times!")
break
main()
main()
while True:
main()
This makes your main method run until you stop it.
You put a break statement in your else. If you remove it it will work. But you also have to put your num statement inside your main.
This should do the job:
def main():
num = random.randint(1, 100)
guess_num = 0
guess = int(input("Enter an integer from 1 to 100: "))
while num != "guess":
if guess < num:
print("Too low, try again.")
guess = int(input("Enter an integer from 1 to 100: "))
guess_num+=1
elif guess > num:
print("Too high, try again.")
guess = int(input("Enter an integer from 1 to 100: "))
guess_num+=1
else:
print("Congratulations, that's correct!")
guess_num = guess_num+1
print("You guessed "+str(guess_num)+" times!")
main()
main()
All lines down from def main(): must be indented four spaces. Maybe it's just a problem with the copy paste, but I find myself really uncomfortable looking at improperly indented Python code.
Remove the print statement right after while num != "guess": not sure what it does
Remove the quotes around guess as right now you're checking a number against a string
Now, to implement your functionality, you should move the num = random.randint(1, 100) line into the function to choose a new number. Then, call the function while true:
while True:
main()

Why does the process just stop even though I have some command? [duplicate]

This question already has answers here:
Python input never equals an integer [duplicate]
(5 answers)
Closed 2 years ago.
I am trying to make a code guessing game where the user can choose the range of the code. The user tries to guess the randomly generated code until he/she gets it right. The computer also shows which digits the user gets correct. The problem is that when the user does guess the code correctly, the process just stops even though my codes says to print a congratulations message and go to the play again function. Please can anyone help? Thanks. Code:
import random
import string
def get_range():
Min = input("ENTER THE MINIMUM NUMBER THE CODE CAN BE: ")
Max = input("ENTER THE MAXIMUM NUMBER THE CODE CAN BE: ")
validate_range(Min, Max)
def validate_range(Min, Max):
Check_Min = Min.isdigit()
Check_Max = Max.isdigit()
if Check_Min is not True or Check_Max is not True:
print("INPUT MUST ONLY INCLUDE INTEGERS! ")
get_range()
elif Min == Max:
print("MINIMUM AND MAXIMUM NUMBER MUST NOT BE EQUIVALENT! ")
get_range()
elif Min > Max:
print("MINIMUM NUMBER MUST NOT BE GREATER THAN MAXIMUM NUMBER!")
get_range()
else:
Random = random.randrange(int(Min), int(Max))
get_guess(Random)
def get_guess(Random):
Guess = str(input("ENTER YOUR GUESS: "))
Check_Guess = Guess.isdigit()
if not Check_Guess:
print("INPUT MUST ONLY CONTAIN INTEGERS! ")
get_guess(Random)
else:
validate_guess(Guess, Random)
def validate_guess(Guess, Random):
Length = len(str(Random))
Digits_Correct = 0
if Guess == Random:
print("WELL DONE! YOU GUESSED THE NUMBER! ")
play_again()
else:
Digits = ["?"] * Length
for i in range(0, int(Length)):
if str(Guess)[i] == str(Random)[i]:
Digits[i] = Guess[i]
Digits_Correct += 1
else:
continue
if int(Length) > Digits_Correct > 0:
print("NOT QUITE! YOU GOT", Digits_Correct, " DIGITS CORRECT!")
print(Digits)
get_guess(Random)
elif Digits_Correct == 0:
print("NONE OF YOUR DIGITS MATCH! ")
get_guess(Random)
def play_again():
Choice = input("\n DO YOU WISH TO PLAY AGAIN? (Y/N)")
if Choice != "Y" or Choice != "N" or Choice != "y" or Choice != "n":
print("PLEASE ENTER A VALID INPUT! ")
play_again()
else:
get_range()
print("WELCOME TO CODE CRUNCHERS!\n ")
get_range()
I think the problem here is that your Guess is a string and your Random is an integer. To fix this, you can try to convert the Guess to an integer or the Random to a string.
Try this:
def validate_guess(Guess, Random):
Length = len(str(Random))
Digits_Correct = 0
if int(Guess) == Random:
print("WELL DONE! YOU GUESSED THE NUMBER! ")
play_again()
I think your problem is with types str and int. First of all your Min and Max are strings, so your line:
elif Min > Max: print("MINIMUM NUMBER MUST NOT BE GREATER THAN MAXIMUM NUMBER!")
does not work correctly. The other problem is that your variables Guess and Random are of different types, so Guess == Random will return False all the time.
Here's correct version of your code.
I've also added a few if cases to be able to quit the program without closing it.
import random
import string
def get_range():
Min = input("ENTER THE MINIMUM NUMBER THE CODE CAN BE: ")
Max = input("ENTER THE MAXIMUM NUMBER THE CODE CAN BE: ")
if Min == 'q':
return
validate_range(Min, Max)
def validate_range(Min, Max):
Check_Min = Min.isdigit()
Check_Max = Max.isdigit()
if Check_Min is not True or Check_Max is not True:
print("INPUT MUST ONLY INCLUDE INTEGERS! ")
get_range()
Min = int(Min)
Max = int(Max)
if Min == Max:
print("MINIMUM AND MAXIMUM NUMBER MUST NOT BE EQUIVALENT! ")
get_range()
elif Min > Max:
print("MINIMUM NUMBER MUST NOT BE GREATER THAN MAXIMUM NUMBER!")
get_range()
else:
Random = random.randrange(int(Min), int(Max))
get_guess(Random)
def get_guess(Random):
Guess = str(input("ENTER YOUR GUESS: "))
Check_Guess = Guess.isdigit()
if not Check_Guess:
print("INPUT MUST ONLY CONTAIN INTEGERS! ")
get_guess(Random)
else:
validate_guess(Guess, Random)
def validate_guess(Guess, Random):
Length = len(str(Random))
Digits_Correct = 0
if int(Guess) == Random:
print("WELL DONE! YOU GUESSED THE NUMBER! ")
play_again()
else:
Digits = ["?"] * Length
for i in range(0, int(Length)):
if str(Guess)[i] == str(Random)[i]:
Digits[i] = Guess[i]
Digits_Correct += 1
else:
continue
if int(Length) > Digits_Correct > 0:
print("NOT QUITE! YOU GOT", Digits_Correct, " DIGITS CORRECT!")
print(Digits)
get_guess(Random)
elif Digits_Correct == 0:
print("NONE OF YOUR DIGITS MATCH! ")
get_guess(Random)
def play_again():
print("\n DO YOU WISH TO PLAY AGAIN? (Y/N)")
Choice = input()
if Choice != "Y" or Choice != "N" or Choice != "y" or Choice != "n":
print("PLEASE ENTER A VALID INPUT! ")
play_again()
else:
get_range()
print("WELCOME TO CODE CRUNCHERS!\n ")
get_range()

User input Exit to break while loop

I'm doing an assignment for the computer to generate a random number and have the user input their guess. The problem is I'm supposed to give the user an option to input 'Exit' and it will break the While loop. What am I doing wrong? I'm running it and it says there's something wrong with the line guess = int(input("Guess a number from 1 to 9: "))
import random
num = random.randint(1,10)
tries = 1
guess = 0
guess = int(input("Guess a number from 1 to 9: "))
while guess != num:
if guess == num:
tries = tries + 1
break
elif guess == str('Exit'):
break
elif guess > num:
guess = int(input("Too high! Guess again: "))
tries = tries + 1
continue
else:
guess = int(input("Too low! Guess again: "))
tries = tries + 1
continue
print("Exactly right!")
print("You guessed " + str(tries) + " times.")
The easiest solution is probably to create a function that gets the displayed message as an input and returns the user input after testing that it fulfils your criteria:
def guess_input(input_message):
flag = False
#endless loop until we are satisfied with the input
while True:
#asking for user input
guess = input(input_message)
#testing, if input was x or exit no matter if upper or lower case
if guess.lower() == "x" or guess.lower() == "exit":
#return string "x" as a sign that the user wants to quit
return "x"
#try to convert the input into a number
try:
guess = int(guess)
#it was a number, but not between 1 and 9
if guess > 9 or guess < 1:
#flag showing an illegal input
flag = True
else:
#yes input as expected a number, break out of while loop
break
except:
#input is not an integer number
flag = True
#not the input, we would like to see
if flag:
#give feedback
print("Sorry, I didn't get that.")
#and change the message displayed during the input routine
input_message = "I can only accept numbers from 1 to 9 (or X for eXit): "
continue
#give back the guessed number
return guess
You can call this from within your main program like
#the first guess
guess = guess_input("Guess a number from 1 to 9: ")
or
#giving feedback from previous input and asking for the next guess
guess = guess_input("Too high! Guess again (or X to eXit): ")
You are trying the parse the string 'Exit' to an integer.
You can add a try/except around the casting line and handle invalid input.
import random
num = random.randint(1,9)
tries = 1
guess = 0
guess = input("Guess a number from 1 to 9: ")
try:
guess = int(guess) // try to cast the guess to a int
while guess != num:
if guess == num:
tries = tries + 1
break
elif guess > num:
guess = int(input("Too high! Guess again: "))
tries = tries + 1
continue
else:
guess = int(input("Too low! Guess again: "))
tries = tries + 1
continue
print("Exactly right!")
print("You guessed " + str(tries) + " times.")
except ValueError:
if guess == str('Exit'):
print("Good bye")
else:
print("Invalid input")

Guessing game: matching user input with randomly generated number

def var (guess):
return guess
guess = int(input("Guess a number 1 through 10: "))
import random
num = (random.randint(1,10))
while True:
try:
guess = num
print("you guessed the right number!")
break
except:
print("try again")
break
So for this program I am trying to figure out how to have the user input a number and to guess what number (1 through 10) the program generated. It seems that every time I input a value it always gives me the "you guess the right number!" string even if I input a value higher than 10.
EDIT: Why would someone downvote my question o_o
You need to get user's input inside while loop so that user's input got updated with each iteration.
import random
num = (random.randint(1,10))
while True:
try:
guess = int(input("Guess a number 1 through 10: "))
if guess == num:
print("you guessed the right number!")
break
else:
print("try again")
except:
print('Invalid Input')
try/except is for exception handling, Not matching values. What you are looking for is if statments, For example:
guess = int(input("Guess a number 1 through 10: "))
import random
num = (random.randint(1,10))
if guess == num:
print("You guessed the right number!")
else:
print("Try again")
I think you may have intended to continue looping until the right number is guessed, In which case, This will work:
import random
num = (random.randint(1,10))
while True:
guess = int(input("Guess a number 1 through 10: "))
if guess == num:
print("You guessed the right number!")
break
else:
print("Try again")

Categories

Resources