Guessing game: matching user input with randomly generated number - python

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")

Related

How to terminate this loop in python?

import random
def validate_user_input(input):
try:
val = int(input)
except ValueError:
print("Please enter a valid input.")
return True
hidden_number = random.randint(1, 10)
user_input = ""
while user_input != hidden_number:
user_input = input("Guess the number from (1 to 1000).")
if validate_user_input(user_input) is True:
continue
else:
if int(user_input) == hidden_number:
print("You have guessed the correct number.", hidden_number)
elif int(user_input) > hidden_number:
print("You have guessed a number higher than the correct number.")
elif int(user_input) < hidden_number:
print("You have guessed a number lower than the correct number.")
else:
print("You have guessed the correct number.")
When the user has inputted the correct number I want the while function to terminate but it instead continues to loop. I tried setting a variable as true in the else function instead but that doesn't work either.
Python 3.5+
The problem is that the input function returns a string, and not an integer. The right way to make your code work without changing it would be to declare user_input as an integer somewhere in the loop. One way to do it to keep the validate_user_input function active and useful would be to put the int() directly in the while declaration, just like this:
import random
def validate_user_input(input):
try:
val = int(input)
except ValueError:
print("Please enter a valid input.")
return True
hidden_number = random.randint(1, 10)
user_input = 0
while int(user_input) != hidden_number:
user_input = input("Guess the number from (1 to 1000)."))
if validate_user_input(user_input) is True:
continue
else:
if int(user_input) == hidden_number:
print("You have guessed the correct number.", hidden_number)
elif int(user_input) > hidden_number:
print("You have guessed a number higher than the correct number.")
elif int(user_input) < hidden_number:
print("You have guessed a number lower than the correct number.")
else:
print("You have guessed the correct number.")

I am getting errors from using try-except block to validate input

I want to use the try-except code block to notify the user not to insert float type values but integers. The code below doesn't throw an error but rather shuts down.
I guess they are logic errors on the try-except block.
userGuess = int(userGuess)
import random
MAX_GUESSES = 5 # max number of guesses allowed
MAX_RANGE = 20 # highest possible number
# show introductionpygame
print("welcome to my franchise guess number game")
print("guess any number between 1 and", MAX_RANGE)
print("you will have a range from", MAX_GUESSES, "guesses")
def playOneRound():
# choose random target
target = random.randrange(1, MAX_RANGE + 1)
# guess counter
guessCounter = 0
# loop fovever
while True:
userGuess = input("take a guess:")
#check for potential errors
try:
userGuess = int(userGuess)
except:
print("sorry, you are only allowed to enter integers thanks!")
# increment guess counter
guessCounter = guessCounter + 1
# if user's guess is correct, congratulate user, we're done
if userGuess == target:
print("you got it la")
print("it only took you", guessCounter, "guess(es)")
break
elif userGuess < target:
print("try again, your guess is too low.")
else:
print(" your guess was too high")
# if reached max guesses, tell answer correct answer, were done
if guessCounter == MAX_GUESSES:
print(" you didnt get it in ", MAX_GUESSES, "guesses")
print("the number was", target)
break
print("Thanks for playing ")
# main code
while True:
playOneRound() # call a function to play one round of the game
goAgain = input("play again?(press ENTER to continue, or q to quit ):")
if goAgain == "q":
break
The task can be split into two steps:
check that the input string can be converted into a number
check that this number is an integer
while True:
userGuess = input("take a guess: ")
try:
userGuess = float(userGuess) # stuff like "asdf", "33ff" will raise a ValueError
if userGuess.is_integer(): # this is False for 34.2
userGuess = int(userGuess)
break # an integer is found, leave the while loop
except ValueError:
pass # just try again
print("sorry, you are only allowed to enter integers thanks!")

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()

Crashing when improper input given more than once

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")

Categories

Resources