Python catch int or str - python

I've written a program that generates a random number for the user to guess. I'm working on trying to catch all the possible errors. The only one I can't seem to figure out is this. At the beginning I ask the user to hit enter to continue to the game. The program catches if they type a string or even special characters and punctuation. The only thing I can't seem to prevent is if they they type a number, the program terminates. This is what I have. The issue is in the first while loop in the try block. Any suggestions or help would be appreciated.
Thanks in advance.
from random import randint #imports randint from random class
cont = input('Press enter to continue')
while True:
if cont != '':
try:
int(cont)
str(cont)
break
except ValueError:
print('Just hit enter')
cont = input()
continue
elif cont == '':
while True:
randNum = randint(1, 100)
print('Try guesssing a number between 1 and 100')
num = input()
while True:
try:
int(num)
break
except ValueError:
print('Please enter a number')
num = input()
int(num)
if num == randNum:
print('Good job, ' + str(num) + ' is correct.')
else:
print('Sorry, the number was ' + str(randNum) + '.')
print('Would you like to try again?')
answer = input().lower()
if answer == 'yes':
continue
elif answer == 'no':
print('Thanks for playing')
exit()
else:
while True:
print('Please type yes or no')
answer = input()
if answer == 'yes':
break
elif answer == 'no':
print('Thanks for playing.')
exit()

What happens when you enter a number is that the program tries to convert the number to an int (which works), and then to a str (which also works), after which it breaks. Instead, try the following:
from random import randint #imports randint from random class
cont = input('Press enter to continue')
while cont != '':
cont = input('Press enter to continue')
while True:
randNum = randint(1, 100)
print('Try guesssing a number between 1 and 100')
num = input()
while True:
try:
int(num)
break
except ValueError:
print('Please enter a number')
num = input()
num = int(num)
if num == randNum:
print('Good job, ' + str(num) + ' is correct.')
else:
print('Sorry, the number was ' + str(randNum) + '.')
print('Would you like to try again?')
answer = input().lower()
if answer == 'yes':
continue
elif answer == 'no':
print('Thanks for playing')
exit()
else:
while True:
print('Please type yes or no')
answer = input()
if answer == 'yes':
break
elif answer == 'no':
print('Thanks for playing.')
exit()

while True:
if cont != '':
try:
int(cont)
str(cont)
break
What it does here is try and convert cont to an int, if it succeeds it tries to convert it to a string (which is virtually always possible). If that succeeds it breaks the while loop and ends the program.
In any other scenario other than an int when it tries to parse it int(cont) it raises an error and you continue to your program.
Once he pressed enter cont starts. there is no reason for you to verify he didn't write something before entering the text.

Related

Can't find a way to incorporate addition, division, subtraction and multiplication inside of my small game

I am trying to use the variables user_ans_a, user_ans_s, user_ans_m and user_ans_d inside of my game as questions randomly chosen by python. My dilemma is coming from matching the randomly chosen variable to an answer coresponding to that variable. I want the user to be able to enter an anser to those questions.
import random
import re
while True:
score = 0
top = "--- Mathematics Game ---"
print(len(top) * "━")
print(top)
print(len(top) * "━")
print(" Type 'Play' to play")
start_condition = "Play" or "play"
def checkint(input_value):
while True:
try:
x = int(input(input_value))
except ValueError:
print("That was a bad input")
else:
return x
while True:
inp = input()
if inp == "Play":
break
else:
print("Try again")
if inp == "Play":
print("What's your name?")
name = input()
print(f"Hello {name}")
while True:
try:
no_of_rounds = int(input("how many rounds do you want to play? "))
break
except ValueError:
print('Please enter a number.')
for i in range(no_of_rounds):
ran_int1 = (random.randint(1,10))
ran_int2 = (random.randint(1,10))
answer_a = (ran_int1 + ran_int2)
answer_s = (ran_int1 - ran_int2)
answer_m = (ran_int1 * ran_int2)
answer_d = (ran_int1 / ran_int2)
user_ans_a = (f"What does {ran_int1} + {ran_int2} = ")
user_ans_s = (f"What does {ran_int1} - {ran_int2} = ")
user_ans_m = (f"What does {ran_int1} * {ran_int2} = ")
user_ans_d = (f"What does {ran_int1} / {ran_int2} = ")
if checkint(user_ans_a) == int(answer_a):
print(f"That was correct {name}.")
score = score+1
else:
print(f"Wrong {name}, the answer was {answer_a}, try again")
print(f"Score was {score}")
while True:
answer = str(input('Run again? (y/n): '))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
continue
else:
print("Goodbye")
break

Asking user whether he/she wants to play again but typing yes just repeats this question again rather starting again

It is a number guessing game
Explanation
At first it asks the user to enter a number between 1 to 50
Then if the number is correct then you win else you have to try again (The winning number is random offcourse)You also have limited guesses
The problem is mentioned below the code
Here is my code:)
import random
winning_num = 23
guesses = 1
guesses_left = 9
game_over = False
end_game = False
number_enter = False
while not end_game:
while not number_enter:
try:
ask = int(input("ENTER A NUMBER BETWEEN 1 AND 50: "))
print(f"TOTAL GUESSES = {guesses_left}")
break
except ValueError:
print("INVALID INPUT!!")
continue
while not game_over:
if ask==winning_num:
print(f"YOU WON BY GUESSING THE NUMBER IN {guesses} TIME(S)!!")
print("DO YOU WANT TO PLAY AGAIN?")
while True:
ask1 = input("ENTER 'YES' OR 'NO' ONLY: ")
ask1 = ask1.lower()
if ask1=='yes':
print("YOU CHOSE TO PLAY AGAIN")
game_over = False
break
elif ask1=="no":
print("THANK YOU FOR PLAYING THIS GAME")
game_over = True
end_game = True
break
else:
print("PLEASE WRITE 'YES' OR 'NO' ONLY ")
continue
elif ask>winning_num:
print("TOO HIGH!!")
guesses+=1
guesses_left-=1
while True:
try:
ask = int(input("TRY AGAIN: "))
print(f"GUESSES LEFT = {guesses_left}")
break
except ValueError:
print("INVALID INPUT!!")
continue
if guesses_left==1:
print("ONLY ONE GUESS LEFT!!")
continue
elif guesses_left==0:
print("YOU LOSE!!")
break
elif ask<winning_num:
print("TOO LOW!!")
guesses+=1
guesses_left-=1
while True:
try:
ask = int(input("TRY AGAIN: "))
print(f"GUESSES LEFT = {guesses_left}")
break
except ValueError:
print("INVALID INPUT!!")
continue
if guesses_left==1:
print("ONLY ONE GUESS LEFT!!")
continue
elif guesses_left==0:
print("YOU LOSE!!")
break
The problem is when the game ends
It asks whether we want to play again
But if we type "Yes" it again asks the same "Do you want to play again"
However typing "No" works fine and the program ends
you have to set game_over = False in case ask1 = yes so that it can come out of the parent while loop and proceed. Also, you'll have to reset number of guesses etc so that it starts as a new game.
import random
winning_num = 23
guesses = 1
guesses_left = 9
game_over = False
end_game = False
number_enter = False
while not end_game:
while not number_enter:
try:
ask = int(input("ENTER A NUMBER BETWEEN 1 AND 50: "))
print(f"TOTAL GUESSES = {guesses_left}")
break
except ValueError:
print("INVALID INPUT!!")
continue
while not game_over:
if ask==winning_num:
print(f"YOU WON BY GUESSING THE NUMBER IN {guesses} TIME(S)!!")
print("DO YOU WANT TO PLAY AGAIN?")
while True:
ask1 = input("ENTER 'YES' OR 'NO' ONLY: ")
ask1 = ask1.lower()
if ask1=='yes':
print("YOU CHOSE TO PLAY AGAIN")
game_over = True
break
elif ask1=="no":
print("THANK YOU FOR PLAYING THIS GAME")
game_over = True
end_game = True
break
else:
print("PLEASE WRITE 'YES' OR 'NO' ONLY ")
continue
elif ask>winning_num:
print("TOO HIGH!!")
guesses+=1
guesses_left-=1
while True:
try:
ask = int(input("TRY AGAIN: "))
print(f"GUESSES LEFT = {guesses_left}")
break
except ValueError:
print("INVALID INPUT!!")
continue
if guesses_left==1:
print("ONLY ONE GUESS LEFT!!")
continue
elif guesses_left==0:
print("YOU LOSE!!")
break
elif ask<winning_num:
print("TOO LOW!!")
guesses+=1
guesses_left-=1
while True:
try:
ask = int(input("TRY AGAIN: "))
print(f"GUESSES LEFT = {guesses_left}")
break
except ValueError:
print("INVALID INPUT!!")
continue
if guesses_left==1:
print("ONLY ONE GUESS LEFT!!")
continue
elif guesses_left==0:
print("YOU LOSE!!")
break
You toggle game_over incorrectly, it should be set to True, not to False if the answer to replay is yes.
while not end_game: # End game must be false to replay
while not number_enter:
#... ask number
while not game_over: # But Game_over should be True to stop asking to replay
#... Check number good
#... Ask to replay
while True:
ask1 = input("ENTER 'YES' OR 'NO' ONLY: ")
ask1 = ask1.lower()
if ask1=='yes':
print("YOU CHOSE TO PLAY AGAIN")
game_over = True # <<<< Thats the problematic part, it must be True
# in your code it is False, So it result in
# an "infinite" loop, if yes.
break

Name 'y' is not defined, python code to find even or odd numbers

I am writing a simple code to find even or odd numbers, the code was working just fine but maybe I did something wrong and it started giving me this error.
File "d:\Python\EvenOddFinder.py", line 12, in restart
restartornot = input()
File "", line 1, in
NameError: name 'y' is not defined
#Even or Odd Number Finder.
def start():
userInput = input("Please input your number:")
userInput = int(userInput)
if userInput %2 == 0:
print("The number " + str(userInput) + " is Even.")
else:
print("The number " + str(userInput) + " is Odd.")
def restart():
print("Do you want to restart?")
print("Y/N")
restartornot = input()
if restartornot == "Y":
start()
elif restartornot == "y":
start()
elif restartornot == "N":
exit()
elif restartornot == "n":
exit()
else:
print("Invalid Input.")
restart()
restart()
start()
Please help me I am quite new to Python.
Assuming you are using Python 2 you should try using
restartornot = raw_input()

Why wont this program stop after I press 'n'?

Why wont this stop when 'n' is entered?
I've tried using break on the bottom else but I get errors doing that. That's a common problem I have with break. I have no idea why I'm thrown off with break.
import random
def game():
secret_num = random.randint(1, 10)
guesses = []
while len(guesses) < 5:
try:
guess = int(input("Guess a number between 1 and 10: "))
except ValueError:
print("{} isn't a number".format(guess))
else:
if guess == secret_num:
print("You got it! The number was {}.".format(secret_num))
break
elif guess < secret_num:
print("My number is higher than {}".format(guess))
else:
print("My number is lower than {}".format(guess))
guesses.append(guess)
else:
print("You didn't get it! My number was {}".format(secret_num))
play_again = input("Do you want to play again? Y/n ")
if play_again.lower() != 'Y':
game()
else:
print("Bye!")
game()
You convert play_again to a lower-case letter but compare it to an upper-case letter.
You could simply change it to:
if play_again.lower() != 'n': # 'y' was wrong, right?
game()
else:
print("Bye!")
return # works also without the explicit return but it makes the intention clearer.

Continuously re-running a while loop until a certain input [duplicate]

This question already has answers here:
If an exception is raised ask again for input
(5 answers)
Closed 9 years ago.
What I'm trying to do with this is ask the user for two inputs and then call a function on the inputs. If it doesn't raise an exception then do the while loop again. If it does raise an exception than print something and do the while loop again. The problem I have is that I can't find a way to do the while loop again if it doesn't raise an exception. It works if it does raise an exception. The only way I can think of it is where I put #Rerun loop paste the entire while True loop again but that would be really horrible in this case.
class Illegal(Exception):
pass
def add_input(first_input, second_input):
if first_input + second_input >= 10:
print('legal')
else:
raise Illegal
def play():
inp = input("Ready? <yes/no>: ")
if inp == 'yes':
while True:
first_input = input("First number: ")
second_input = input("Second number: ")
try:
if first_input or second_input == 'quit':
break
else:
add_input(int(first_input), int(second_input))
#Rerun loop
except Illegal:
print("Illegal")
else:
break
else:
return
>>> play()
Ready? <yes/no>: yes
First number: 1
Second number: 2
Illegal
First number: 9
Second number: 6
legal
First number: 1
Second number: 2
Illegal
First number: quit
What I thought of doing:
def play():
inp = input("Ready? <yes/no>: ")
if inp == 'yes':
while True:
first_input = input("First number: ")
second_input = input("Second number: ")
try:
if first_input or second_input == 'quit':
break
else:
add_input(int(first_input), int(second_input))
while True:
first_input = input("First number: ")
except Illegal:
print("Illegal move")
else:
break
except Illegal:
print("Illegal move")
else:
break
else:
return second_input = input("Second number: ")
try:
if first_input or second_input == 'quit':
break
else:
add_input(int(first_input), int(second_input))
#Rerun loop
But this is a horrible idea because then I'd have to paste the same thing continuously.
The break in your else: causes the loop to exit. You can remove this entirely:
else:
break
You want to run the loop while the user doesn't quit it via typing quit. So you just have to remove this else: break:
def play():
inp = input("Ready? <yes/no>: ")
if inp.lower() == 'yes':
while True:
first_input = input("First number: ")
second_input = input("Second number: ")
# quit if the user wants
if first_input or second_input == 'quit':
break
try:
add_input(int(first_input), int(second_input))
except Illegal:
print("Illegal")
Also, take the habit to put the minimum of code in your try/except blocks. It makes the debugging easier after. Your last else: return is also useless, you can remove it.

Categories

Resources