How could I use the except function with a for loop - python

When there is a wrong answer, I would like a preset message for all the operators to be displayed.
Maybe something like this:
while True:
try:
user_ans = int(input())
except ValueError:
print ("That is not a valid answer")
continue
else:
break
but in a for loop.
My aim is to ask numerical questions then save to a file.
First, I need to ask the user what maths class they are in, then ask 10 randomly generated questions.
#Imports
import random
from time import sleep
#List & Definitions#
operators = ("-","+","X")
score = 0
QA = 0
#Intro#
print ("Hello and Welcome")
print ("What is your name?")
name = input ()
print ("Do you want to Play (Yes/No)?")
choice = input()
if choice =="Yes":
print ("Excellent")
if choice == "No":
print ("Okey, bye...")
end()
quit()
print ("Please input your class")
cn = input ()
print ("Let's start the quiz!")
sleep(2)
#Asking Questions
for QA in range (0, 10):
numb1 = random.randint(1,10)
numb2 = random.randint(1,10)
randOp = random.choice(operators)
#Addition
if randOp == "+" :
print (str(numb1) + "+" + str(numb2))
answer = numb1 + numb2
print ("Please input your answer")
UserAns = int(input ())
if UserAns == answer :
print ("well done that was correct")
score = score + 1
if UserAns != answer:
print("that's wrong")
else:
print ("Oops! That was no valid number. Try again...")
#Subtracting
if randOp == "-" :
if numb2 > numb1 :
print (str(numb2) + "-" + str(numb1))
answer = numb2 - numb1
print ("Please input your answer")
UserAns = int(input ())
if UserAns == answer :
print ("woah again Correct")
if UserAns != answer:
print("that's wrong")
score = score + 1
elif numb1 > numb2 :
print(str(numb1) + "-" + str(numb2))
answer = numb1 - numb2
print ("Please input your answer")
UserAns = int(input ())
if UserAns == answer :
print ("Correct :) ")
score = score + 1
if UserAns != answer:
print("that's wrong")
#Multiplication
if randOp == "*" :
print (str(numb1) + "X" + str(numb2))
ans = numb1 * numb2
sleep(1)
print ("Please input your answer")
UserAns = int(input ())
if ans == UserAns :
print ("Correct")
score = score + 1
if UserAns != answer:
print("that's wrong")
#Displaying Score
QA = QA + 1
if QA == 10 :
print ("Your score is " + str(score) + " out of ten")
#Saving & Writing to File
savePath = "Results\Class " + str(cn) + "\\" + name.lower() +".txt"
file = open(savePath, "a")
file.close()
file = open(savePath, "r")
if file.read() == "":
file.close()
file = open(savePath, "a")
file.write(name + "\n\n")
file.close()
file.close()
file = open(savePath, "a")
file.write(str(score))
file.write("\n")
file.close()

Just make better input functions..
def input_with_choices(prompt, choices):
while True:
choice = input('{} (choices are: {}) '.format(prompt, ','.join(choices)))
if choice in choices:
return choice
else:
print("That's not a valid choice.")
and
def input_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("That's not an integer.")
etc.
Then you can use those to validate your input in the for loop.

Your question isn't very understandable, however, what I think you are looking for is this:
accepted = False
while not accepted:
try:
UserAns = int(input())
accepted = True
except:
pass

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

Python guessing game code keeps crashing after 1 guess. How would i fix this?

My code keeps crashing after I put in the 1st guess I make. I've looked at syntax and dont think that's a problem how do I make it so it goes past the 1st guess and executes it. When I put the guess in it just puts in all the prompts at once, and how do I call the function properly at the end? Any help would be appreciated.
Import time,os,random
def get_int(message):
while True:
user_input = input(message)
try:
user_input = int(user_input)
print('Thats an integer!')
break
except:
print('That does not work we need an integer!')
return user_input
def game_loop():
fin = False
while not fin:
a = get_int('give me a lower bound:')
b = get_int('give me a upper bound:')
if a < 0:
print("that doesn't work")
if a > b:
a, b = b, a
print(a,b)
os.system('clear')
print("The number you guess has to be between " + str(a) + "and " + str(b) + '.')
num_guesses = 0
target = random.randint(a,b)
time_in = time.time()
while True:
print('You have guessed ' + str(num_guesses) + " times.")
print()
guess_input = get_int('guess a number')
if guess_input == target:
print("Congrats! You guessed the number!")
time_uin = time.time()
break
elif guess_input < a or guess_input > b:
print("guess was out of range... + 1 guess")
elif guess_input < target:
print("Your guess was too low")
else:
print("Your guess was to high")
num_guesses = num_guesses + 1
if num_guesses<3:
print('Einstein?')
else:
print('you should be sorry')
time_t = time_uin - time_in
print('it took' + str(time_t) + 'seconds for you to guess a number')
print()
time_average = time_t / (num_guesses+1)
print('It took an average of' + str(time_average)+"seconds per question")
print()
while True:
play_again = input ('Type y to play again or n to stop')
print()
if play_again == 'n':
fin = True
print('Thank God')
time.sleep(2)
os.system('clear')
break
elif play_again == 'y':
print('here we go again')
time.sleep(2)
os.system('clear')
break
else:
print('WRONG CHOCICE')
break
game_loop()
If guess_input != target on the first iteration of the loop, time_uin is referenced before assignment. Hence the error:
UnboundLocalError: local variable 'time_uin' referenced before assignment
Solution is to run the following only if guess_input == target.
if num_guesses<3:
print('Einstein?')
else:
print('you should be sorry')
time_t = time_uin - time_in
print('it took' + str(time_t) + 'seconds for you to guess a number')
print()
time_average = time_t / (num_guesses+1)
print('It took an average of' + str(time_average)+"seconds per question")
print()
Please follow coppereyecat's link to learn how to debug a basic Python program.

Return to another part of a loop

I am learning python and I cannot figure out how to get back to a certain part of loop depending on the response.
If it reaches:
else :
print('Answer must be yes or no')
I want it to start back at:
print ("We are going to add numbers.")
I have tried several different suggestions I have seen on here, but they result in starting back at the very beginning.
My code:
import random
num1 = random.randint(1,100)
num2 = random.randint(1,100)
addition = num1 + num2
print("Hello. What is your name?")
name = str(input())
print ("Nice to meet you " + name)
print ("We are going to add numbers.")
print ("Does that sound good?")
answer = str.lower(input())
if answer == str('yes'):
print ('Yay!!')
print ('Add these numbers')
print (num1, num2)
numbers = int(input())
if numbers == addition:
print('Good Job!')
else:
print('Try again')
numbers = int(input())
elif answer == str('no'):
print ('Goodbye')
else :
print('Answer must be yes or no')
You need a loop that starts with the thing you want to get back to:
def start():
import random
num1 = random.randint(1, 100)
num2 = random.randint(1, 100)
addition = num1 + num2
print("Hello. What is your name?")
name = str(input())
print("Nice to meet you " + name)
while True:
print("We are going to add numbers.")
print("Does that sound good?")
answer = str.lower(input())
if answer == "no":
print("Goodbye")
return
elif answer == "yes":
break
else:
print('Answer must be yes or no')
print('Yay!!')
print('Add these numbers')
print(num1, num2)
# This following part might want to be a loop too?
numbers = int(input())
if numbers == addition:
print('Good Job!')
else:
print('Try again')
numbers = int(input())

Python - while loop semi works depending on where i start on the menu

i am a super beginner to python.
Below is a simple math quiz. The problem is that selecting option 2 (subtraction) then 1 (addition) shuts down the program instead of asking addition problem.
It works from 1 to 2 but it does not work from 2 to 1. Do you guys know what i am missing here? Thanks in advance.
while user_input == 1:
num1 = (random.randrange(0,100))
num2 = (random.randrange(0,100))
answer = num1 + num2
problem = str(num1) + " + " + str(num2)
print("Enter your answer")
print(problem, end="")
result = int(input(" = "))
if result == answer:
print('Correct')
else:
print('Incorrect')
user_input = int(input('Enter your choice: '))
subtraction for choice 2
while user_input == 2:
num1 = (random.randrange(0,100))
num2 = (random.randrange(0,100))
answer = num1 - num2
problem = str(num1) + " - " + str(num2)
print("Enter your answer")
print(problem, end="")
result = int(input(" = "))
if result == answer:
print('Correct')
else:
print('Incorrect')
user_input = int(input('Enter your choice: '))
Exit for choice 3 - the User is done with the quiz
else:
print('See you again')
For good practice and readability, I would implement something like:
choice = input()
while choice != -1:
choice = input()
if choice == 1:
#do something
else if choice == 2:
#do something else
else if choice == -1:
print("bye")
Your code is wrong. You must do something like this:
choice = input()
while choice == "1" or choice == "2":
if choice == "1":
#do add
else:
#do subtraction
choice = input()
print("bye")

Python - Returning variable from function trouble

I'm currently learning Python and am creating a maths quiz.
I have created a function that loops, first creating a random maths sum, asks for the answer and then compares the input to the actual answer; if a question is wrong the player loses a point - vice versa. At the end a score is calculated, this is what I'm trying to return at the end of the function and print in the main.py file where I receive a NameError 'score' is not defined.
I have racked my head on trying to figure this out. Any help / suggestions would be greatly appreciated!
#generateQuestion.py
`def generate(lives, maxNum):
import random
score= 0
questionNumber = 1
while questionNumber <=10:
try:
ops = ['+', '-', '*', '/']
num1 = random.randint(0,(maxNum))
num2 = random.randint(0,10)
operation = random.choice(ops)
question = (str(num1) + operation + str(num2))
print ('Question', questionNumber)
print (question)
maths = eval(str(num1) + operation + str(num2))
answer=float(input("What is the answer? "))
except ValueError:
print ('Please enter a number.')
continue
if answer == maths:
print ('Correct')
score = score + 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
elif lives == 1:
print ('You died!')
print('\n')
break
else:
print ('Wrong answer. The answer was actually', maths)
lives = lives - 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
if questionNumber == 0:
print ('All done!')
return score
`
My main file
#main.py
import random
from generateQuestion import generate
#Welcome message and name input.
print ('Welcome, yes! This is maths!')
name = input("What is your name: ")
print("Hello there",name,"!" )
print('\n')
#difficulty prompt
while True:
#if input is not 1, 2 or 3, re-prompts.
try:
difficulty = int (input(' Enter difficulty (1. Easy, 2. Medium, 3. Hard): '))
except ValueError:
print ('Please enter a number between 1 to 3.')
continue
if difficulty < 4:
break
else:
print ('Between 1-3 please.')
#if correct number is inputted (1, 2 or 3).
if difficulty == 1:
print ('You chose Easy')
lives = int(3)
maxNum = int(10)
if difficulty == 2:
print ('You chose Medium')
lives = int(2)
maxNum = int(25)
if difficulty == 3:
print ('You chose Hard')
lives = int(1)
maxNum = int(50)
print ('You have a life count of', lives)
print('\n')
#generateQuestion
print ('Please answer: ')
generate(lives, maxNum)
print (score)
#not printing^^
'
I have tried a different method just using the function files (without the main) and have narrowed it down to the problem being the returning of the score variable, this code is:
def generate(lives, maxNum):
import random
questionNumber = 1
score= 0
lives= 0
maxNum= 10
#evalualates question to find answer (maths = answer)
while questionNumber <=10:
try:
ops = ['+', '-', '*', '/']
num1 = random.randint(0,(maxNum))
num2 = random.randint(0,10)
operation = random.choice(ops)
question = (str(num1) + operation + str(num2))
print ('Question', questionNumber)
print (question)
maths = eval(str(num1) + operation + str(num2))
answer=float(input("What is the answer? "))
except ValueError:
print ('Please enter a number.')
continue
if answer == maths:
print ('Correct')
score = score + 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
elif lives == 1:
print ('You died!')
print('\n')
break
else:
print ('Wrong answer. The answer was actually', maths)
lives = lives - 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
if questionNumber == 0:
return score
def scoreCount():
generate(score)
print (score)
scoreCount()
I think the problem is with these last lines in main:
print ('Please answer: ')
generate(lives, maxNum)
print ('score')
You are not receiving the returned value. It should be changed to:
print ('Please answer: ')
score = generate(lives, maxNum) #not generate(lives, maxNum)
print (score) # not print('score')
This will work.
The way it works is not:
def a():
score = 3
return score
def b():
a()
print(score)
(And print('score') will simply print the word 'score'.)
It works like this:
def a():
score = 3
return score
def b():
print(a())

Categories

Resources