Python, guess my number game [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
import random
print("hello, what is your name?")
GG = input()
print("well, " + GG + ", I am thinking of a number between 0 and 20")
number = random.randint(0,20)
try:
for taken in range(1,7):
print("Take a guess.")
guess = int(input())
if guess < number:
print("your guess is too low.")
elif guess > number:
print("your guess is too high.")
else:
break
except ValueError:
print("please enter a valid number")
if guess == number:
print("good job, "+ GG + " you guessed my number in " + str(taken) + " guesses")
else:
print("nope,the number i was thinking of was " + str(number))
If I want everytime when the player types an invalid input and the "Take a guess" game continues, how can I do?

Design
I think that you should separate, as far as possible, the two issues of looping on the responses and getting a validated response, and you can achieve this by writing a function that handles the problem of validating the user input.
Such a function needs to know how to prompt the user and what to tell the user if their input is invalid, so we must provide two arguments to the function, but we provide also reasonable defaults for the arguments...
To look at the correctness of the input, we use a try: ... except: ... clause, if the body of try raises an error, except looks at the error and if it is a particular one (for us, ValueError) the body of the except is executed.
The body of the except ends with a call to the function that we are defining, because this is another way of looping, if you consider what is happening... and in this case it is a simpler way of looping.
Implementation
That said, with the understanding of what we need in our function, we write it:
def get_integer(prompt='Enter an integer: ',
err_prompt='Not an integer, please try again.'):
answer = input(prompt)
try:
number = int(answer)
return number
except ValueError:
print(err_prompt)
return get_integer(prompt, err_prompt)
Testing
And now a bit of testing,
In [19]: get_integer()
Enter an integer: 1
Out[19]: 1
In [20]: get_integer()
Enter an integer: a
Not an integer, please try again.
Enter an integer: 1
Out[20]: 1
In [21]: get_integer(prompt='Un numero intero, per favore: ')
Un numero intero, per favore: 23.2
Not an integer, please try again.
Un numero intero, per favore: 22
Out[21]: 22
In [22]: get_integer(err_prompt='Naaaah!')
Enter an integer: q
Naaaah!
Enter an integer: 11
Out[22]: 11
In [23]:
Putting it all together
I've used your implementation, because for sure it is good enough, but I've changed a little the capitalization of the strings, no more try ... except as this is hidden in get_integer() and the introduction of an else clause to the for loop that is executed on normal termination, so that your user is informed of the reason why the program is stopping.
import random
def get_integer(prompt='Enter an integer: ',
err_prompt='Not an integer, please try again.'):
answer = input(prompt)
try:
return int(answer)
except ValueError:
print(err_prompt)
return get_integer(prompt, err_prompt)
print("Hello, what is your name?")
GG = input()
print("Well, " + GG + ", I am thinking of a number between 0 and 20...")
number = random.randint(0,20)
for taken in range(1,7):
print("Take a guess.")
guess = get_integer()
if guess < number:
print("Your guess is too low.")
elif guess > number:
print("Your guess is too high.")
else:
print("Your guess is exact!")
break
else:
print("Too many attempts. You lose!")

Wrap your input in some kind of while loop.
def checkIsValid(value):
#some validity checking function here.
‌
for taken in range(1,7):
print("Take a guess.")
guess = input()
isValid = checkIsValid(guess)
while (not isValid):
print("Invalid input")
guess = input()
isValid = checkIsValid(guess)
guess = int(guess)
#continue with the valid value.

'''
Created on 2016-3-24
#author: GuangFa
'''
import random
def get_name():
"""
Get name from the input.
:Usage:
get_name()
"""
print("hello,what is your name?")
name=raw_input()
return name
def get_number():
"""
Get number from the input.Return the number until the input is a valid number
:Usage:
get_number()
"""
is_number=False
while not is_number:
try:
number=input('please enter a valid number:')
except Exception ,e:
is_number=False
else:
is_number=True
return number
def guess():
"""
Guess the number.The system generates a random number,
Only 7 chances to guess the number.
:Usage:
guess()
"""
name=get_name()
print("well,%s, I am thinking of a number between 0 and 20"%name)
number = random.randint(0,20)
for taken in range(1,7):
print("Take a guess.")
guess=get_number()
if number==guess:
print ("good job, %s you guessed my number in %s guesses"%(name,str(taken)) )
break
if guess < number:
print("your guess is too low.")
elif guess > number:
print("your guess is too high.")
if taken==6:
print "nope,the number i was thinking of was " + str(number)
guess()

Related

Is there a way to make an integer input output a certain thing when a sting or float is inputted? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed last year.
Here is my code:
x = 1
while x == 1:
fav_number = int(input("Guess my favorite number: "))
print()
if fav_number == 8:
print("Gongrats, you guessed it!")
x = 2
else:
print("Nope, try again!")
print()
In this example, I want it to also say "Nope, try again!" when the user inputs in a float or a string without crashing the program.
while True:
try: #Use the try/except block to raise exception if value is not integer
fav_number = int(input("Guess my favorite number: "))
print()
except ValueError: # if value is anything but integer, exception is raised
print("Invalid entry. Try again.")
else:
if fav_number == 8:
print("Gongrats, you guessed it!")
break #code ends when number is guessed
else:
print("Nope, try again!")
To make it more interesting, you can add a predefined number of attempts. If attempts are exhausted, code stops:
attempts = 5
while attempts > 0:
attempts -= 1
try: #Use the try/except block to raise exception if value is not integer
fav_number = int(input("Guess my favorite number: "))
print()
except ValueError: # if value is anything but integer, exception is raised
print("Invalid entry. Try again.")
else:
if attempts > 0:
if fav_number == 8:
print("Gongrats, you guessed it!")
break #code ends when number is guessed
else:
print("Nope, try again!")
print(f"You have {attempts} left")
else:
print("You have exhausted your attempts.")
You can, use eval in python for the string would convert int to int and float to float without exception. Check the documentation here: https://docs.python.org/3/library/functions.html#eval
So basically you can change the int to eval:
x = 1
while x == 1:
fav_number = eval(input("Guess my favorite number: "))
print()
if fav_number == 8:
print("Gongrats, you guessed it!")
x = 2
else:
print("Nope, try again!")
print()

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 can I end a function in Python just like using "return" in c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Hello I am a Python fresher and I wanna use the feature "return" just like in c++. You know that if I "return" in c++, the whole main function will stop, but it seems that in Python "return" can only be used in function. I tried to use "exit" to replace it but I don't know why it still executed the "except" part. Is there anything wrong with my code? Thank you very much!
name=input("Please input your name? ")
print("Hello,", name)
year=input("Please input your birth year? ")
try:
age=2007-int(year)
if age <= 25:
print("Welcome home! You have 5 chances to win the prize. ")
for i in range (1, 5):
luckynumber=input("Please input an random number? ")
if int(luckynumber) == 66:
print("Congratulation! Fist Prize!")
exit(0)
elif int(luckynumber) == 88:
print("Not bad! Second Prize! ")
exit(0)
else:
print("Best luck for next turn!")
print("Sorry, you didn't win. ")
else:
print("Get out!")
except:
print("Your birth-year or luckynumber must be an integer")
Try this, this worked fine for me
def my_func():
name=raw_input("Please input your name? ")
print("Hello,", name)
year=raw_input("Please input your birth year? ")
try:
age=2007-int(year)
if age <= 25:
print("Welcome home! You have 5 chances to win the prize. ")
for i in range (1, 5):
luckynumber=input("Please input an random number? ")
if int(luckynumber) == 66:
return("Congratulation! Fist Prize!")
elif int(luckynumber) == 88:
return("Not bad! Second Prize! ")
else:
print("Best luck for next turn!")
return("Sorry, you didn't win. ")
else:
return("Get out!")
except:
return("Your birth-year or luckynumber must be an integer")
print my_func()
Output:
Please input your name? Stackoverflow
('Hello,', 'Stackoverflow')
Please input your birth year? 1985
Welcome home! You have 5 chances to win the prize.
Please input an random number? 25
Best luck for next turn!
Please input an random number? 35
Best luck for next turn!
Please input an random number? 45
Best luck for next turn!
Please input an random number? 66
Congratulation! Fist Prize!
I am not sure of C++ if you want to write the function separately and main separately it can be done like this
def function_name(args):
#function code
pass
#main function
if __name__=="__main__":
# calling the function
function_name(1)
Example:
def my_func():
name=raw_input("Please input your name? ")
print("Hello,", name)
year=raw_input("Please input your birth year? ")
try:
age=2007-int(year)
if age <= 25:
print("Welcome home! You have 5 chances to win the prize. ")
for i in range (1, 5):
luckynumber=input("Please input an random number? ")
if int(luckynumber) == 66:
return("Congratulation! Fist Prize!")
elif int(luckynumber) == 88:
return("Not bad! Second Prize! ")
else:
print("Best luck for next turn!")
return("Sorry, you didn't win. ")
else:
return("Get out!")
except:
return("Your birth-year or luckynumber must be an integer")
if __name__=="__main__":
print my_func()
The exit function is provided by the sys module, which needs to be imported:
import sys
sys.exit(0)
Elsewise you can wrap your code in function and use the return statement:
def main():
name=input("Please input your name? ")
print("Hello,", name)
year=input("Please input your birth year? ")
try:
age=2007-int(year)
if age <= 25:
print("Welcome home! You have 5 chances to win the prize. ")
for i in range (1, 5):
luckynumber=input("Please input an random number? ")
if int(luckynumber) == 66:
print("Congratulation! Fist Prize!")
return
elif int(luckynumber) == 88:
print("Not bad! Second Prize! ")
return
else:
print("Best luck for next turn!")
print("Sorry, you didn't win. ")
else:
print("Get out!")
except:
print("Your birth-year or luckynumber must be an integer")
if __name__ == '__main__':
main()
As a sidenote when you remove try/except, the interpreter is going to show you which and where an error appeared.
Another option would be to import the traceback module and use traceback.print_exec() in the except block.

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

Validate that integer is typed

I've looked up several of these questions and can't seem to apply it to my code correctly. I'm definitely new to Python and developed a number guessing game for practice. The last error handling I need is to make sure that anything typed that is not an integer, will return an error message. I was hoping to use an "if" statement like I have for other conditions, but will work with what I can get. Thanks!
(this is just a snippet. i didn't include the entire program)
def gamestart():
print(rndnumber)
for GuessAmount in range (1,11):
ActualGuess = int(input("Guess number " + str(GuessAmount) + ": "))
if ActualGuess < rndnumber:
print("HIGHER!")
if ActualGuess > rndnumber:
print("LOWER!")
if ActualGuess != rndnumber:
GuessAmount == GuessAmount + 1
if ActualGuess == rndnumber:
print("You Win!")
gameend()
print("")
print("Sorry, but you ran out of guesses.")
print("")
gameend()
Use try/except:
while True:
guess = input("Guess number " + str(GuessAmount) + ": ")
try:
guess_int = int(guess)
break
except ValueError:
print "please enter only integers"
Now you have your (converted to integer) input in guess_int.
If it was impossible to convert the input to integer, user gets warning and enters number once again.

Categories

Resources