if op == '+':
left1 = random.randint(1,100)
right1 = random.randint(1,100)
print ("What is " + (str(left1) + op + str(right1) + "?"))
answer = eval(str(left1) + op + str(right1))
guess = int(input(""))
if guess == answer:
print("Correct!")
score + 1
elif guess != answer:
print("Incorrect")
else:
except ValueError:
print("Expected integer")
I tried except ValueError, but it stated that it was invalid syntax. I'm trying to get the code to force the user to enter an integer for the answer, if they don't then it tells them that they are supposed to enter an integer.
ValueError is not a function; it is a class (an Exception subclass).
You need to use except as part of a try statement, it cannot be used on its own; you need to put any code you want 'protected' inside the try:
if op == '+':
left1 = random.randint(1,100)
right1 = random.randint(1,100)
print ("What is " + (str(left1) + op + str(right1) + "?"))
answer = eval(str(left1) + op + str(right1))
try:
guess = int(input(""))
except ValueError:
print("Expected integer")
else:
if guess == answer:
print("Correct!")
score = score + 1 # don't forget to *store* the sum!
else:
print("Incorrect")
You probably want to read the canonical Stack Overflow question on user input in Python to learn more about this: Asking the user for input until they give a valid response, as well as the section on handling exceptions in the Python tutorial.
Related
So I can't really figure out why the variables "first" and "second" aren't defined even when returning them it doesn't work maybe I'm doing it wrong I honestly have no clue.
The assignment is to make a times table tester using only functions to give us an understanding of functions.
My teacher gave us what the functions are supposed to do so I will put these below.
def results_summary(right, answered):
""" right is int for number of correct questions
answered is int rep. total number of questions
display results of practice with ratio
and percentage correct """
def generate_question():
""" generate and display a random multiplication
questions with factors from 1 to 12
return the answer as an integer value """
def get_answer():
""" display = to prompt user to enter answer
returns input if valid integer entry is made
displays message and new prompt for invalid entry """
def goAgain():
""" Asks the user y/n if they want another question
returns True for 'y' and False for 'n'
displays message and new prompt for invalid entry """
Any help would be greatly appreciated!
import random
#defines important functions
def results_summary(num_correct, num_question):
percentage = num_correct / num_question * 100
correctCount = str(num_correct)
questionCount = str(num_question)
percentage = str(round(percentage))
print('You got ' + correctCount + '/' + questionCount + ' (' + percentage + '%).')
def generate_question():
first = random.randint(1,12)
second = random.randint(1,12)
correct_answer = second * first
return correct_answer
def get_answer():
try:
user_answer = input('What is ' + first + ' x ' + second + '?')
except ValueError:
print('Please Enter Integers Only.')
def goAgain():
input('Do you want another question? (y / n)')
try:
'y' == True
'n' == False
except ValueError:
print('Please Enter a valid response. (y / n)')
#MAIN PROGRAM
num_correct = 0
num_question = 0
#creates while loop to continuously ask questions
while True:
correct_answer = generate_question()
user_answer = get_answer()
#prints if the user answers correctly
if user_answer == correct_answer:
print('Correct')
num_question += 1
num_correct += 1
again = goAgain()
if goAgain == False:
break
results_summary(num_correct, num_question)
I'm so sorry budd :(
I got no time to explain ... [I'm in a hurry] but I don't want you to get disrespect from your teacher !, I been there :/
So here is the modified working code , hope it helps :)
import random
#defines important functions
def results_summary(num_correct, num_question):
percentage = (num_correct / num_question) * 100
print(f"You got {round(percentage)} %")
def generate_question():
global first
global second
first = random.randint(1,12)
second = random.randint(1,12)
correct_answer = second * first
return correct_answer
def get_answer():
try:
user_answer = int(input('What is ' + str(first) + ' x ' + str(second) + '?'))
return user_answer
except ValueError:
print('Please Enter Integers Only.')
def goAgain():
confo = input('Do you want another question? (y / n)')
if confo.lower() == 'y':
return True
elif confo.lower() == "n":
return False
else:
return
#MAIN PROGRAM
num_correct = 0
num_question = 0
#creates while loop to continuously ask questions
while True:
correct_answer = generate_question()
user_answer = get_answer()
#prints if the user answers correctly
if user_answer == correct_answer:
print('Correct')
num_question += 1
num_correct += 1
else:
num_question += 1
print("Wrong answer")
again = goAgain()
if again:
pass
else:
print("Have a great day!, bye")
break
if goAgain == False:
break
results_summary(num_correct, num_question)
The error shows variables first and second to be undefined because the variables you are using in:
user_answer = input('What is ' + first + ' x ' + second + '?')
command inside the get_answer() function, are undefined.
In order to use these variables, just change the function generate_question() to:
def generate_question():
global first, second
first = random.randint(1,12)
second = random.randint(1,12)
correct_answer = second * first
return correct_answer
and change the input command inside get_answer() function to:
user_answer = input('What is ' + str(first) + ' x ' + str(second) + '?')
I'm doing some Python exercises and I came across a frustrating error:
line 18, in <module>
modulo()
NameError: name 'modulo' is not defined
Code is below:
number = input("Please enter a number: ")
if number.isdigit():
def modulo():
answer = int(number) % 2
if answer == 0:
print("Your number, " + number + " is even.")
elif answer > 0:
print("Your number, " + number + " is odd.")
else:
print("Error. Please try again.")
else:
print("Please try again")
modulo()
Make modulo accept an argument, define it outside the if-statement
def modulo(num):
answer = int(num) % 2
if answer == 0:
print("Your number, " + num + " is even.")
elif answer > 0:
print("Your number, " + num + " is odd.")
else:
print("Error. Please try again.")
number = input("Please enter a number: ")
if number.isdigit():
modulo(number)
else:
print("Please try again")
You should write your function outside the if statement, in this case the function will be defined ONLY if number.isdigit() is True.
This is my code.
print("Welcome to the quiz")
print("Would you like to login with an existing account or register for a new account?")
class validation(Exception):
def __init__(self, error):
self.error = error
def printError(self):
print ("Error: {} ".format(self.error))
def mainError():
try:
raise validation('Please enter a valid input')
except validation as e:
e.printError()
def login():
print ("yet to be made")
def register():
print ("yet to be made")
while True:
options = ["Login", "Register"]
print("Please, choose one of the following options")
num_of_options = len(options)
for i in range(num_of_options):
print("press " + str(i + 1) + " to " + options[i])
uchoice = int(input("? "))
print("You chose to " + options[uchoice - 1])
if uchoice == 1:
login()
break
elif uchoice == 2:
register()
break
else:
mainError()
If I enter 'a', it comes up with this error:
line 35, in <module>
uchoice = int(input("? "))
ValueError: invalid literal for int() with base 10: 'a'
If I enter a number above 2 like '3':
line 36, in <module>
print("You chose to " + options[uchoice - 1])
IndexError: list index out of range
How can I make sure that if a user enters anything other than 1 or 2, it executes my else commands where it calls my mainError() method which contains my exception that the program would display to my user.
The exception is raising because you don't have the options element you're trying to print in the message
print("You chose to " + options[uchoice - 1])
Here you're trying to get options[a] or options [3], which doesn't exists.
Put this print only inside the if/else that has a related option, and another print in the else without one.
Something like this:
for i in range(num_of_options):
print("press " + str(i + 1) + " to " + options[i])
uchoice = int(input("? "))
if uchoice == 1:
print("You chose to " + options[uchoice - 1])
login()
break
elif uchoice == 2:
print("You chose to " + options[uchoice - 1])
register()
break
else:
mainError()
uchoice = int(input("? "))
Well here you have to do some error-checking code like:
try:
uchoice = int(input("? "))
except ValueError:
<handling for when the user doesn't input an integer [0-9]+>
Then to handle the overflow when a user enters an index which isn't within the list's range:
try:
options[uchoice - 1]
except IndexError:
<handling for when the user inputs out-of-range integer>
Of course this adds overhead due to the try: ... except <error>: ... statement so in the most optimal case you would use conditional checking per something like this:
if (uchoice - 1) > len(options):
<handling for when the user inputs out-of-range integer>
I have this problem when i run the program it all goes good an all, but when a user gets the right answer, the code does not print neither print("Good Job!") or print("Correct"). what is wrong with the code ?
import random
firstNumber = random.randint(1, 50)
secondNumber = random.randint(1, 50)
result = firstNumber + secondNumber
result = int(result)
print("Hello ! What\'s your name ? ")
name = input()
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
userAnswer = int(input("Your answer : "))
while (userAnswer != result) :
if (userAnswer > result) :
print("Wrong")
else:
print("Wrong")
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
input("\n\n Press to exit")
The problem is that your while-loop will only run as long as the first answer is wrong. Everything that is indented after while (userAnswer != result) will be ignored by Python if the first answer is right. So logically a first correct answer can never reach print("Correct"), since that would require the answer to be both wrong (to start the while loop) and right (to get to "Correct").
One option is to get rid of the while-loop, and just use if's. You get two chances this way, then you lose.
if (userAnswer == result):
print("Well done!")
else:
print("Wrong")
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
else:
print("Nope all wrong you lose")
Another option is to make an infinite loop using While. (like #csharpcoder said)
while (True) :
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print ("Wrong answer")
In the last option a wrong answer gets "Wrong answer" and the while-loop starts again, since True is of course still True. So you try again, until you get the right answer, which will bring you to "correct, good job" and then break (which stops the loop).
I struggled with while-loops and kind of getting it in my head that indentation means Python will treat it as 'one thing' and skip it all if I start it with something that's False.
If the answer is correct, then
while (userAnswer != result) :
will cause the loop contents to be skipped.
First of all, you get input outside of your loop and then don't do anything with it. If your answer is correct on the first try, you will get no output because userAnswer != result will be False immediately and your while loop won't run.
Some other points:
if (userAnswer > result) :
print("Wrong")
else:
print("Wrong")
is redundant because you are guaranteed to fall into one of these, as you will only get here if the answer is wrong (and therefore > or < result). Just print "Wrong" without a condition, as the only reason this would run is if the answer was wrong.
print("Correct")
print("Good Job!")
You can use \n to print on a new line instead of having multiple print statements together. Usually you only use multiple prints together for readability, but print("Correct\nGood job!") isn't that much less readable.
if (userAnswer == result):
#...
break
You don't need break here because the answer is already correct and the loop won't repeat anyway.
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
Here, you append string literals to string literals ("Hello!" + " "). You don't need to do that as you can just write "Hello! ".
result = firstNumber + secondNumber
result = int(result)
The result (pun not intended) is already an integer, so you don't need to convert it.
How about using a infinite while loop something like this :
while (True) :
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print ("Wrong answer")
In your logic if you enter the wrong answer first time and correct answer afterwards , then it will work as per your requirement , but if you enter the correct answer first time it will simple skip the while loop .
I played around a bit to refactor, in an attempt to make it more clear:
import random
name = input("Hello ! What's your name? ")
print("Hello, {name}!".format(name=name))
print("Ok, {name}, let's start!".format(name=name))
first_number = random.randint(1, 50)
second_number = random.randint(1, 50)
correct_answer = first_number + second_number
print("What is, '{first} + {second}'?".format(first=first_number,
second=second_number))
user_answer = None
while user_answer != correct_answer:
try:
user_answer = int(input("Your answer : ")) # ValueError will be raised if non integer value given
except ValueError:
print("Invalid Input!")
user_answer = None
if user_answer:
if user_answer == correct_answer:
print("Correct")
print("Good Job!")
else:
print('--> Wrong, try again!')
input("\n<< Press any key to exit >>")
#This will loop the try statement until an integer is entered as the guess1 variable
while True:
#The try statement will see if the guess variable is given an integer value,
#if not then it will print "You did not enter an integer. This is not a
#valid answer
try:
#This will allow the user to enter their answer and
#store it in the guess1 variable
guess1 = int(input(""))
#This will break the while loop if an integer is entered as the guess1 variable
break
except ValueError:
print("You did not enter an integer. This is not a valid answer. Please enter a valid integer")
print("Answer the quesiton appropiately" + "What is " + (str(first2) + op + str(second2) + "?")
if guess1 == answer1:
#If the guess1 variable is equal to the answer1 variable, then
#"Correct!" will be printed and one point would be
#added to the score
print("Correct!")
score += 1
else:
#Else "Incorrect" would be printed
print ("Incorrect")
The shell states that there is an invalid syntax with the colon when I typed 'guess1 == answer1:'.
The problem is that you didn't close a tag on the second line in your except statement. Add an extra ")" to the end.
print("Answer the quesiton appropiately" + "What is " + (str(first2) + op + str(second2) + "?"))