I'm a python beginner and i was making a simple number guessing game, but every time i accidently type in a letter or a symbol instead of a number, i get the ValueError. How do I pass this error throughout the entire program? i know the code is messy, and I'm sorry for that but I'm just trying to have some fun with it.
import random
tries = 15
money = 0
cheat = 0
run = True
random_number = random.randint(1, 20)
while run:
if cheat >= 1:
print(random_number)
cheat -= 1
guess = input("Pick a number from 1-20! You have " + str(tries) + " tries")
guess = int(guess)
if guess == random_number:
money += 5
print("You got it right! You got it with " + str(tries) + " tries left", "your balance is", + money)
again = input("Play again? yes/no")
if again == "yes":
random_number = random.randint(1, 20)
else:
break
#store system
shop = input("Would you like to access the shop? yes/no")
if shop == "yes":
try_cost = 10
cheat_cost = 20
#if player has enough money
buy_try = input("Would you like to purchase more tries? price is 10 dollars for 5 tries. yes/no")
if buy_try == "yes" and money >= 10:
tries += 5
money -= 10
print("You have", tries, "tries", "and", money, "money", "and", cheat, "cheats")
buy_cheat = input("Would you like to purchase a cheat? price is 20 dollars for 2 cheats")
if buy_cheat == "yes" and money >= 20:
cheat += 2
money -= 20
print("You have", tries, "tries", "and", money, "money", "and", cheat, "cheats")
# if player doesn't have enough money
elif buy_try == "yes" and money != 10:
print("You don't have enough for that, you have", money, "dollars")
elif buy_cheat == "yes" and money != 20:
print("You don't have enough for that, you have", money, "dollars")
elif guess > random_number:
print("Try a little lower!")
tries -= 1
elif guess < random_number:
print("Try a little higher!")
tries -= 1
if tries == 0:
print("you ran out of tries!")
run = False
Pick a number from 1-20! You have 15 triess
Traceback (most recent call last):
File "C:\Users\bashr\PycharmProjects\pythonProject1\main.py", line 15, in
guess = int(guess)
ValueError: invalid literal for int() with base 10: 's'
In this situation, use a try and except clause.
Documentation: https://docs.python.org/3/tutorial/errors.html#handling-exceptions
assuming you want to access that error inside this whole file then you can use global variable or you can use class concept
I think the fastest way to solve that is a while: while the input Is not a digit ask again the input.
So, in your case, every time you use the input function you should use something likes this:
guess = input("Pick a number from 1-20! You have " + str(tries) + " tries")
while not guess.isdigit():
print("the input Is not a digit, please retry")
guess = input("Pick a number from 1-20! You have...")
Or you can use you can use try and except
Related
I am working on Guess the number program in Python. I had to make some enhancements to it and add:
User has a default limit of 15 guesses (when enter key is hit)
Ask for a limit to the number of guests - this part doesn't work in my code.
import random
def main():
print('\n'*40)
print('Welcome to the Guess number game!')
print('\n'*1)
player_name = input("What is your name? ") print('\n'*1)
try_again = 'y'
number_of_guesses = 0
error = 0
guess_limit = 15
while ((try_again == 'y') or (try_again == 'Y')):
try:
limit = input('You have 15 default guesses to start. Do you like to have different number of guesses? ')
if limit.upper() == 'Y':
limit = input('How many times would you like to play? ') # after I input number of guesses I cannot proceed to the actual game
else:
number = random.randint(1, 100)
while (guess_limit != 0):
guess = int(input("Enter an integer from 1 to 100: "))
if (guess < 1) or (guess > 100):
print("ERROR! Integer must be in the range 1-100! ")
else:
if guess < number:
print ("Guess is low!")
elif guess > number:
print ("Guess is high!")
else:
print('\n'*1)
print ("YOU WIN! You made " + str(number_of_guesses) + " guesses.")
break
number_of_guesses += 1
guess_limit -= 1
print(guess_limit, 'guesses left')
print()
else:
#if guess_limit == 0:
print ("YOU LOSE! You made " + str(number_of_guesses) + " guesses.")
except ValueError:
print('ERROR: Non-numeric data. Please enter valid number!')
print('\n'*1)
try_again = input("Play again? Enter 'Y' or 'y' for yes: ")
print('\n'*1)
main()
OUTPUT: Welcome to the Guess number game!
What is your name? d
You have 15 default guesses to start.
Do you like to have different number of guesses? y
How many times would you like to play? 3 # after this I have
Play again? Enter 'Y' or 'y' for yes: # this result
How can I change that code?
you have to use
guess_limit = input("How many times would you like to play? ")
and then you have to check if it is blank or not by simple if conditions
if guess_limit == "":
guess_limit = 15
Below is the full code with well commented.
# import only system from os
from os import system
import random
def main():
# For clearing the screen
system('cls')
# For adding blank line
blank_line = '\n'*1
print('Welcome to the Guess number game!')
print(blank_line)
player_name = input("What is your name? ")
print(blank_line)
# to start the loop initially try_again = 'y'
try_again = 'y'
# Count number of guesses by player
number_of_guesses = 0
while (try_again.lower() == 'y'):
# Get number of times player want to guess
guess_limit = input("How many times would you like to play? ")
# If player enter nothing and hit enter
# then default value of guess_limit is 15
if guess_limit == "":
guess_limit = 15
# Convert the guess_limit to int data type
guess_limit = int(guess_limit)
# If user inputted number then go inside this try block
# else go inside except block
try:
# Generate random number in betwee 1-99 to be guess by the player
number = random.randint(1, 99)
# Loop untill there is no guesses left
while (guess_limit != 0):
# Player guess
guess = int(input("Enter an integer from 1 to 99: "))
# Check for valid number i.e number should be betwee 1 - 99
while ((guess < 1) or (guess > 99)):
guess = int(
input("ERROR! Please enter an integer in the range from 1 to 99: "))
# Check for High and low guess
if guess < number:
print("Guess is low")
elif guess > number:
print("Guess is high")
# If it is neither high nor low
else:
print(blank_line)
print("YOU WIN! You made " +
str(number_of_guesses) + " guesses.")
# To get out of the loop
break
# decrement the guess_limit by 1 on every iteration
guess_limit -= 1
print(guess_limit, 'guesses left')
# Increment number of guesses by the player
number_of_guesses += 1
print()
# If guess_limit is equal to 0, it means player have not guessed the number
# And player lose
if guess_limit == 0:
print("YOU LOSE! You made " +
str(number_of_guesses) + " guesses.")
except ValueError:
print('ERROR: Non-numeric data. Please enter valid number!')
print(blank_line)
# Ask again to play again
# If player enter anything other than 'Y' or 'y' then exit the game
try_again = input("Play again? Enter 'Y' or 'y' for yes: ")
print(blank_line)
main()
I'm a beginner in Python and I was wondering why this keeps looping, can someone help me out. When I print it out, it stays in a loop even tho I guessed the number right
import random
answer = random.randint(1,10)
lives = 5
out_of_lives = 0
print("Hi there! What is your name? ")
name = input()
print("Alright " + name + ", we're playing guess the number between 0 and 20.")
guess = int(input("Take a guess: "))
while (lives != 0) or (guess != answer):
if guess > answer:
print("Guess lower!")
lives = lives - 1
print("You have got", lives, "lives left")
guess = int(input('Try again, your new guess: '))
elif guess < answer:
print("Guess higher")
lives = lives - 1
print("You have got", lives , "lives left")
guess = int(input('Try again, your new guess: '))
elif guess == answer:
print("Good job, you guessed the number")
elif lives == 0:
print("Game over!, I was thinking about the number: ", answer)
Because you are not breaking the while loop.
One way to solve your problem is by inserting the conditions whether the user guessed the right number inside a main if condition of the guess is not the answer. And then break the loop when the user succeed. Like the following:
import random
answer = random.randint(1,10)
lives = 5
out_of_lives = 0
print("Hi there! What is your name? ")
name = input()
print("Alright " + name + ", we're playing guess the number between 0 and 20.")
guess = int(input("Take a guess: "))
while (lives > 1):
if guess != answer:
if guess > answer:
print("Guess lower!")
lives = lives - 1
print("You have got", lives, "lives left")
guess = int(input('Try again, your new guess: '))
elif guess < answer:
print("Guess higher")
lives = lives - 1
print("You have got", lives , "lives left")
guess = int(input('Try again, your new guess: '))
else:
print("Good job, you guessed the number")
break
print("Game over!, I was thinking about the number: ", answer)
yes this is because you also need to break the loop just where you want it to stop.
On the condition that the game is won, no adjustment to life or answers is set meaning you get stuck in the while loop.
It is because of the conditions of your while loop. You wrote that "Keep going if you have lives remain or you are wrong". So it will not stop when you still have lives even if you guessed correct, or it will not stop writing "Game over" as you did not guessed right. The right thing to do is to change the loop condition as: while (lives !=0) and (guess != answer):
Here's the correct code. Execute it. It'll solve your issue
import random
answer = random.randint(1,10)
lives = 5
out_of_lives = 0
print("Hi there! What is your name? ")
name = input()
print("Alright " + name + ", we're playing guess the number between 0 and 20.")
guess = int(input("Take a guess: "))
while(True):
if(lives==1):
print("Game over!, I was thinking about the number: ", answer)
break
else:
if guess == answer:
print("Good job, you guessed the number")
break
elif guess > answer:
print("Guess lower!")
lives = lives - 1
print("You have got", lives, "lives left")
guess = int(input('Try again, your new guess: '))
elif guess < answer:
print("Guess higher")
lives = lives - 1
print("You have got", lives , "lives left")
guess = int(input('Try again, your new guess: '))
Im getting a syntax error for elif option ==2:. I was wondering what I need to do to fix it. I followed the pseudocode my professor gave us but it still won't run. I'm wondering if I shouldn't have used elif or maybe something about the indentation is off.
import random
print("Welcome to the guess my number program")
while True:
print("1. You guess the number")
print("2. You type a number and see if the computer can guess it")
print("3. Exit")
option = int(input("Please enter your number here: "))
if option ==1:
#generates a random number
mynumber = random.randint(1,11)
#number of guesses
count = 1
while True:
try:
guess = int(input("Guess a number between 1 and 10:"))
while guess < 1 or guess > 10:
guess = int(input("Guess a number between 1 and 10:")) # THIS LINE HERE
except:
print("Numbers Only")
continue
#prints if the number you chose is too low and adds 1 to the counter
if guess < mynumber:
print("The number you chose is too low")
count= count+1
#prints if the number you chose is too high and adds 1 to the counter
elif guess > mynumber:
print("The number you choose is too high")
count = count+1
#If the number you chose is correct it will tell you that you guessed the number and how many attempts it took
elif guess == mynumber:
print("You guessed it in " , count , "attempts")
break
elif option == 2:
number = int(input("Please Enter a Number: "))
count = 1
while True:
randomval = random.randint(1,11)
if (number < randomval):
print("Too high")
elif (number > randomval):
print("Too low")
count = count+1
elif (number==randomval):
print("The computer guessed it in" + count + "attempts. The number was" + randomval)
break
else:
break
The problem is simple. There is no continuity between if option == 1 and elif option == 2, because of the in between while loop. What you have to do is remove the el part of elif option == 2 and just write if option == 2.
I haven't tested the whole program myself. But at a glance, this should rectify the problem.
Please comment if otherwise.
i recently started learning python and my friend from work who is a programmer gave me a simple challenge to write a "guess the number" style game.
So i came up with something as follows:
import random
print("Hello, welcome to GUESS THE NUMBER game")
run = True
def again():
global run
playagain = str(input("Would you like to play again? Type y/n for yes or no: "))
if playagain == "y":
run = True
elif playagain == "n":
run = False
while run:
guess = int(input("Guess the number between 1 and 10: "))
num1 = random.randint(1, 10)
if guess == num1:
print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
again()
elif guess > num1:
print("Too high, go lower!")
elif guess < num1:
print("Too small, go higher!")
My problem is that after the user has chosen to play again, the numbers sometimes dont register and go out of whack. For example you input 5 and it says too low, but if you input 6 it says too high! I don't seem to be dealing in float numbers so they should be whole, any ideas where i went wrong?
Thanks in advance and very excited to learn more on the subject
Your problem is that you're regenerating the random number every time.
num1 = random.randint(1, 10)
Instead, maybe put the guess and check logic inside it's own loop.
while True:
guess = int(input("Guess the number between 1 and 10: "))
if guess == num1:
print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
break # leave the while True loop
elif guess > num1:
print("Too high, go lower!")
elif guess < num1:
print("Too small, go higher!")
again()
You are calculating the random number on each iteration of the loop. Therefore every time you guess the random number changes.
import random
print("Hello, welcome to GUESS THE NUMBER game")
run = True
def again():
global run
playagain = str(input("Would you like to play again? Type y/n for yes or no: "))
if playagain == "y":
run = True
elif playagain == "n":
run = False
num1 = random.randint(1, 10)
while run:
guess = int(input("Guess the number between 1 and 10: "))
if guess == num1:
print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
again()
elif guess > num1:
print("Too high, go lower!")
elif guess < num1:
print("Too small, go higher!")
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