I am very knew to Python, so as expected, I'm encountering problems often when scripting and am usually not sure how to fix them.
I'm making a small game where you try and guess a number which the program has randomly chosen. I've gotten pretty far, but I noticed the program simply displayed an error message when I input nothing. I would like the program to display the text "Enter a number." in this situation, and then prompt the "Your guess: " input again, but after a lot of research, I'm really not sure how to successfully implement that feature into my code. My issue, specifically, is the "try and except" section - I don't really know how to write them properly, but I saw another post on here suggesting to use them.
import random
def question():
print("Guess a number between 1 and 100.")
randomNumber = random.randint(1, 100)
found = False
while not found:
myNumber = int(input("Your guess: "), 10)
try:
myNumber = int(input("Your guess: "), 10)
except ValueError:
print("Enter a number.")
if myNumber == randomNumber:
print("Correct!")
found = True
elif myNumber > randomNumber:
print("Wrong, guess lower!")
else:
print("Wrong, guess higher!")
question()
You should be able to see my intentions in the code I've written, thanks.
You're almost right. Just continue to the next iteration after handling exception.
import random
def question():
print("Guess a number between 1 and 100.")
randomNumber = random.randint(1, 100)
found = False
while not found:
try:
myNumber = int(input("Your guess: "), 10)
except Exception:
print('Enter a number.')
continue
if myNumber == randomNumber:
print("Correct!")
found = True
elif myNumber > randomNumber:
print("Wrong, guess lower!")
else:
print("Wrong, guess higher!")
question()
You can write a function like this:
def input_num(input_string):
""" This function collects user input
Args:
input_string: message for user
Return:
user_input: returns user_input if it is a digit
"""
user_input = raw_input("{}: ".format(input_string))
if not user_input.isdigit():
input_num(input_string)
return int(user_input)
then call this function
user_num = input_num("Enter a number")
It will keep asking a user to provide a valid input until user puts one
I'm confused why you ask for the input twice. You only need to ask them for input once. After that, you need to add a continue to your except statement. Otherwise, it will not repeat and just end the program. This is what your modified while loop should look like.
while not found:
try:
myNumber = int(input("Your guess: "), 10)
except ValueError:
print("Enter a number.")
continue
if myNumber == randomNumber:
print("Correct!")
found = True
elif myNumber > randomNumber:
print("Wrong, guess lower!")
else:
print("Wrong, guess higher!")
Just use the continue keyword in your except to continue the loop.
except ValueError:
print('Enter a number')
continue
Related
This is my first post in StackOverFlow and I'm sure that I can find for 100% percent an answer for it, but I'd really like to start my adventure with programming and know that this community might help me with it.
My questions are:
I wrote that first piece of code but I'd like to add here a function where the user writes the guess number bigger than the first one.
I am troubled with adding the additional function if for this situation - I do understand that it wouldn't suppose to be if, but elif.
Is anyone has any idea how to suppose to look-alike??
import random
top_range = input("Write a number bigger then 0: ")
if top_range.isdigit() or top_range[0] == "-":
top_range = int(top_range)
if top_range <= 0:
print('Write a number bigger then 0')
quit()
else:
print('Write a number bot a word')
quit()
random_number = random.randint(0, top_range)
guesses = 0
while True:
guesses += 1
user_guess = input("Guess the number : ")
if user_guess.isdigit():
user_guess = int(user_guess)
else:
print('Write another number.')
continue
if user_guess == random_number:
print('You did it!')
break
else:
if user_guess < random_number:
print('The number is bigger then that')
else:
print('The number is smaller than that')
print('You did it in', guesses, "guesses!")
Add a first if, then use elif for the other choices. I've also simplify a bit the first if
while True:
guesses += 1
user_guess = input("Guess the number : ")
if not user_guess.isdigit():
print('Write another number.')
continue
user_guess = int(user_guess)
if user_guess > top_range:
print("That is higher than top range, try again")
elif user_guess == random_number:
print('You did it!')
break
elif user_guess < random_number:
print('The number is bigger then that, try again')
else:
print('The number is smaller than that, try again')
I want this number guessing game to be able to catch every possible exception or error the user enters. I've successfully prevented the use of strings when guessing the number, but I want the console to display a custom message when a float is entered saying something along the lines of "Only whole numbers between 1-20 are allowed". I realize my exception would work to catch this kind of error, but for learning purposes, I want to specifically handle if the user enters a float instead of an int. From what I could find online the isinstance() function seemed to be exactly what I was looking for. I tried applying it in a way that seemed logical, but when I try to run the code and enter a float when guessing the random number it just reverts to my generalized exception. I'm new to Python so if anyone is nice enough to assist I would also appreciate any criticism of my code. I tried making this without much help from the internet. Although it works for the most part I can't get over the feeling I'm being inefficient. I'm self-taught if that helps my case lol. Here's my source code, thanks:
import random
import sys
def getRandNum():
num = random.randint(1,20)
return num
def getGuess(stored_num, name, gameOn = True):
while True:
try:
user_answer = int(input("Hello " + name + " I'm thinking of a number between 1-20. Can you guess what number I'm thinking of"))
while gameOn:
if user_answer >= 21 or user_answer <=0:
print("That is not a number between 1-20. Try again.")
user_answer = int(input())
elif isinstance(user_answer, int) != True:
print("Only enter whole numbers. No decimals u cheater!")
user_answer = int(input())
elif user_answer > stored_num:
print("That guess is too high. Try again " + name + " !")
user_answer = int(input())
elif user_answer < stored_num:
print("That guess is too low. Try again " + name + " !")
user_answer = int(input())
elif user_answer == stored_num:
print("You are correct! You win " + name + " !")
break
except ValueError:
print("That was not a number, try again")
def startGame():
print("Whats Your name partner?")
name = input()
stored_num = getRandNum()
getGuess(stored_num, name)
def startProgram():
startGame()
startProgram()
while True:
answer = input("Would you like to play again? Type Y to continue.")
if answer.lower() == "y":
startProgram()
else:
break
quit()
The only thing that needs be in the try statement is the code that checks if the input can be converted to an int. You can start with a function whose only job is to prompt the user for a number until int(response) does, indeed, succeed without an exception.
def get_guess():
while True:
response = input("> ")
try:
return int(response)
except ValueError:
print("That was not a number, try again")
Once you have a valid int, then you can perform the range check to see if it is out of bounds, too low, too high, or equal.
# The former getGuess
def play_game(stored_num, name):
print(f"Hello {name}, I'm thinking of a number between 1-20.")
print("Can you guess what number I'm thinking of?")
while True:
user_answer = get_guess()
if user_answer >= 21 or user_answer <=0:
print("That is not a number between 1-20. Try again.")
elif user_answer > stored_num:
print(f"That guess is too high. Try again {name}!")
elif user_answer < stored_num:
print(f"That guess is too low. Try again {name}!")
else: # Equality is the only possibility left
print("You are correct! You win {name}!")
break
I making a quiz program using Python 3. I'm trying to implement checks so that if the user enters a string, the console won't spit out errors. The code I've put in doesn't work, and I'm not sure how to go about fixing it.
import random
import operator
operation=[
(operator.add, "+"),
(operator.mul, "*"),
(operator.sub, "-")
]
num_of_q=10
score=0
name=input("What is your name? ")
class_num =input("Which class are you in? ")
print(name,", welcome to this maths test!")
for _ in range(num_of_q):
num1=random.randint(0,10)
num2=random.randint(1,10)
op,symbol=random.choice(operation)
print("What is",num1,symbol,num2,"?")
if int(input()) == op(num1, num2):
print("Correct")
score += 1
try:
val = int(input())
except ValueError:
print("That's not a number!")
else:
print("Incorrect")
if num_of_q==10:
print(name,"you got",score,"/",num_of_q)
You need to catch the exception already in the first if clause. For example:
for _ in range(num_of_q):
num1=random.randint(0,10)
num2=random.randint(1,10)
op,symbol=random.choice(operation)
print("What is",num1,symbol,num2,"?")
try:
outcome = int(input())
except ValueError:
print("That's not a number!")
else:
if outcome == op(num1, num2):
print("Correct")
score += 1
else:
print("Incorrect")
I've also removed the val = int(input()) clause - it seems to serve no purpose.
EDIT
If you want to give the user more than one chance to answer the question, you can embed the entire thing in a while loop:
for _ in range(num_of_q):
num1=random.randint(0,10)
num2=random.randint(1,10)
op,symbol=random.choice(operation)
while True:
print("What is",num1,symbol,num2,"?")
try:
outcome = int(input())
except ValueError:
print("That's not a number!")
else:
if outcome == op(num1, num2):
print("Correct")
score += 1
break
else:
print("Incorrect, please try again")
This will loop eternally until the right answer is given, but you could easily adapt this to keep a count as well to give the user a fixed number of trials.
Change
print("What is",num1,symbol,num2,"?")
if int(input()) == op(num1, num2):
to
print("What is",num1,symbol,num2,"?")
user_input = input()
if not user_input.isdigit():
print("Please input a number")
# Loop till you have correct input type
else:
# Carry on
The .isdigit() method for strings will check if the input is an integer.
This, however, will not work if the input is a float. For that the easiest test would be to attempt to convert it in a try/except block, ie.
user_input = input()
try:
user_input = float(user_input)
except ValueError:
print("Please input a number.")
This question already has answers here:
Ask the user if they want to repeat the same task again
(2 answers)
Closed 4 years ago.
Basically it's a guessing game and I have literally all the code except for the last part where it asks if the user wants to play again. how do I code that, I use a while loop correct?
heres my code:
import random
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
while guess == number:
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == yes:
guess= eval(input("Enter your guess between 1 and 1000 "))
if again == no:
break
One big while loop around the whole program
import random
play = True
while play:
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
play = False
separate your logic into functions
def get_integer_input(prompt="Guess A Number:"):
while True:
try: return int(input(prompt))
except ValueError:
print("Invalid Input... Try again")
for example to get your integer input and for your main game
import itertools
def GuessUntilCorrect(correct_value):
for i in itertools.count(1):
guess = get_integer_input()
if guess == correct_value: return i
getting_close = abs(guess-correct_value)<10
if guess < correct_value:
print ("Too Low" if not getting_close else "A Little Too Low... but getting close")
else:
print ("Too High" if not getting_close else "A little too high... but getting close")
then you can play like
tries = GuessUntilCorrect(27)
print("It Took %d Tries For the right answer!"%tries)
you can put it in a loop to run forever
while True:
tries = GuessUntilCorrect(27) #probably want to use a random number here
print("It Took %d Tries For the right answer!"%tries)
play_again = input("Play Again?").lower()
if play_again[0] != "y":
break
Don't use eval (as #iCodex said) - it's risky, use int(x). A way to do this is to use functions:
import random
import sys
def guessNumber():
number=random.randint(1,1000)
count=1
guess= int(input("Enter your guess between 1 and 1000: "))
while guess !=number:
count+=1
if guess > (number + 10):
print("Too high!")
elif guess < (number - 10):
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = int(input("Try again "))
if guess == number:
print("You rock! You guessed the number in ", count, " tries!")
return
guessNumber()
again = str(input("Do you want to play again (type yes or no): "))
if again == "yes":
guessNumber()
else:
sys.exit(0)
Using functions mean that you can reuse the same piece of code as many times as you want.
Here, you put the code for the guessing part in a function called guessNumber(), call the function, and at the end, ask the user to go again, if they want to, they go to the function again.
I want to modify this program so that it can ask the user whether or not they want to input another number and if they answer 'no' the program terminates and vice versa. This is my code:
step=int(input('enter skip factor: '))
num = int(input('Enter a number: '))
while True:
for i in range(0,num,step):
if (i % 2) == 0:
print( i, ' is Even')
else:
print(i, ' is Odd')
again = str(input('do you want to use another number? type yes or no')
if again = 'no' :
break
#My code should take a random between 1 and 100 and let you guess it.
#This part works, but I want to add the posibility to reveal the number and then is when I get the error "could not convert string to float"
def reveal(guess):
return secret_number
import random
secret_number = random.random()*100
guess = float(input("Take a guess: ")) #This is the input
while secret_number != guess :
if guess < secret_number:
print("Higher...")
elif guess > secret_number:
print("Lower...")
guess = float(input("Take a guess: ")) #This input is here in order for the program not to print Higher or Lower without ever stopping
else:
print("\nYou guessed it! The number was " ,secret_number)
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
print ("Number was", secret_number)
input("\n\n Press the enter key to exit")
Any help would be a great service. Also I am only programming for just a few weeks so sorry if my code looks wrong.
If you want to use float number to compare, the game may be endless because a float number has many fractional digits. Use int number.
#!/usr/bin/env python3.3
# coding: utf-8
import random
def guess_number():
try:
guess = int(input("Take a guess:"))
except ValueError:
print("Sorry, you should input a number")
guess = -1
return guess
if __name__ == '__main__':
secret_number = int(random.random() * 100)
while True:
guess = guess_number()
if guess == -1:
continue
elif guess < secret_number:
print("Lower...")
elif guess > secret_number:
print("Higher...")
else:
print("\nYou got it! The number was ", secret_number)
input("\n\nPress any key to exit.")
break # or 'import sys; sys.exit(0)'
import random
LOWEST = 1
HIGHEST = 100
def main():
print('Guess the secret number between {} and {}!'.format(LOWEST, HIGHEST))
secret = random.randint(LOWEST, HIGHEST)
tries = 0
while True:
guess = raw_input('Your guess: ').strip().lower()
if guess.isdigit():
tries += 1
guess = int(guess)
if guess < secret:
print('Higher!')
elif guess > secret:
print('Lower!')
else:
print('You got it in {} tries!'.format(tries))
break
elif guess == "reveal":
print('The secret number was {}'.format(secret))
break
else:
print('Please enter a number between {} and {}'.format(LOWEST, HIGHEST))
if __name__=="__main__":
main()
Use random.range instead of random.random.
secret_number = random.range(1,100,1)
And ...,str(secret_number)
...
else:
print("\nYou guessed it! The number was " ,str(secret_number))
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
print ("Number was", str(secret_number))
...
That way you will be concatenating a string with a string. Also, you can keep random.random and only make the second change.
EDIT:
Another thing to do is to use raw_input instead of input. Then use try.
guess = raw_input("Take a guess: ")
try:
guess = float(guess)
except:
pass
This will try to convert guess into a float, and it that fails, then it will remain a string. That should solve your problem.
You could isolate concerns by defining a function that asks user for input until a float is provided:
def input_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("You should input a float number. Try again.")
Then you could use it in your script:
guess = input_float("Take a guess: ")
If you want to accept 'reveal' as an input in addition to a float number:
def input_float_or_command(prompt, command='reveal'):
while True:
s = input(prompt)
if s == command:
return s
try:
return float(s)
except ValueError:
print("You should input a float number or %r. Try again." % command)