Being an absolute beginner, I'm facing some issues in my simple math quiz in python.
First Issue:
In my programme, the answer is stuck with option d only, i want to swap the correct option between the choice a-d every time.
Second Issue:
i declare a variable "score" and i try to increment it's value on each correct answer, but it's is not updating.
Third Issue :
I want to clear Previous question on selecting correct option and ask a new question.
My code is :
import random
def myFunction():
score=0
num1= random.randint(0,1000)
num2= random.randint(1,1000)
num2=num1
if num1==num2:
num2=num2+random.randint(0,50)
print(num1, "+" , num2, "= ?")
result=num1+num2
option1=result+random.randint(1,25)
option2=result+random.randint(1,25)
option3=result+random.randint(1,25)
d=result
print("(a)", option1)
print("(b)", option2)
print("(c)", option3)
print("(d)", result)
value= input("Select the correct option \n Answer:")
if value=="d":
print("Correct Answer...!!")
score+=1 #update score
myFunction()
else:
result="d"
print("Wrong Answer, Correct option is ","(",result,")")
print("Your Score is : ", score)
exit()
myFunction()
This code works with following changes:
You should use a while loop to iteratively get a response from user (otherwise you will eventually exceed recursion depth)
It continues on wrong answers
Stops on the first correct answer
If you enters a blank line then it also stops (i.e. providing user a way to exit the program)
Code
import platform
import os
import sys
import random
def clear():
'''
Clears console
'''
system_ = platform.system()
print('system_', system_)
if system_ == 'Windows':
os.system('cls')
else:
# Linux or Mac
os.system('clear')
def myFunction():
score=0
# Use while loop rather than recusively calling function
while True:
# Select two numbers
num1= random.randint(0,1000)
num2= random.randint(1,1000)
if num1==num2:
num2=num2+random.randint(0,50)
print('clear the screen')
clear() # Clear console
print(num1, "+" , num2, "= ?")
result = num1 + num2 # the answer for sum
option1 = result + random.randint(1,25)
option2 = result + random.randint(1,25)
option3 = result+random.randint(1,25)
# options for sum
options = [option1, option2, option3, result]
# Place options in random order
random.shuffle(options)
choices = "abcd"
for choice, option in zip(choices, options):
print(f"{choice} {option}")
value= input("Select the correct option (or blank line to quit) \n Answer:")
while value and value not in choices: # checks for blank line and if entry in choices
print("Select letter from ", *choices)
value= input("Select the correct option (or blank line to quit\n Answer:")
if value is None:
# Blank line
print(f'Final score was {score}')
break # done with while loop
index = choices.index(value)
if options[index] == result:
print("Correct Answer...!!")
score += 1 #update score
print(f"Your Score is : {score}")
else:
print(f"Wrong Answer, Correct option is ({result})")
print(f"Your Score is : {score}")
myFunction()
I don't know how you want your code to work. But I edited your code as below. Once you entered wrong answer you will be out of from quiz.
import random
def myFunction():
global score
num1= random.randint(0,1000)
num2= random.randint(1,1000)
# num2=num1
if num1==num2:
num2=num2+random.randint(0,50)
print(num1, "+" , num2, "= ?")
result=num1+num2
option1=result+random.randint(1,25)
option2=result+random.randint(1,25)
option3=result+random.randint(1,25)
d=result
choice = [option1,option2,option3,result]
random.shuffle(choice)
print("(a)", choice[0])
print("(b)", choice[1])
print("(c)", choice[2])
print("(d)", choice[3])
value= input("Select the correct option \n Answer:")
if (value == "a" and d == choice[0]) or (value == "b" and d == choice[1]) or (value == "c" and d == choice[2]) or (value == "d" and d == choice[3]):
print("Correct Answer...!!")
score+=1 #update score
else:
result= d
print("Wrong Answer, Correct option is ","(",result,")")
print("Your Score is : ", score)
exit()
score = 0
while True:
myFunction()
print("Score : ", score)enter code here
This code first stores the answer in a random option, and then the answer variable is given the value of the option, i.e a,b,c or d. I added the score variable as a parameter to the function and every time a correct answer is given the value of the parameter will be set equal to the score
import random
def myFunction(score=0):
num1 = random.randint(0,1000)
num2 = random.randint(1,1000)
if num1==num2:
num2=num2+random.randint(0,50)
print(num1, "+" , num2, "= ?")
result=num1+num2
option1=result+random.randint(1,25)
option2=result+random.randint(1,25)
option3=result+random.randint(1,25)
option4=result+random.randint(1,25)
answer = random.randint(1,5)
if answer==1:
option1 = result
answer = 'a'
if answer==2:
option2 = result
answer = 'b'
if answer==3:
option3 = result
answer = 'c'
if answer==4:
option4 = result
answer = 'd'
print("(a)", option1)
print("(b)", option2)
print("(c)", option3)
print("(d)", option4)
value= input("Select the correct option \n Answer:")
if value==answer:
print("Correct Answer...!!")
score = score + 1 #update score
myFunction(score)
else:
result=answer
print("Wrong Answer, Correct option is ","(",result,")")
print("Your Score is : ", score)
exit()
myFunction()
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 10 months ago.
#for project 2
# division
def divide(a, b):
return (a / b)
# palindrome
def isPalindrome(s):
return s == s[::-1]
print("Select operation.")
print("1. Divide")
print("2. Palindrome")
print("3. Square root")
while True:
choice = input("Enter choice(1/2/3): ")
if choice == '1':
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print(num1, "/", num2, "=", divide(num1, num2))
elif choice == '2':
def isPalindrome(s):
return s == s[::-1]
s = str(input("Enter word:"))
ans = isPalindrome(s)
if ans:
print (s+" "+"is a palindrome.")
else:
print (s+" "+"is not a palindrome.")
elif choice == '3':
threenumber = float(input("Enter a number: "))
sqrt = threenumber ** 0.5
print ("The square root of " + str(threenumber) + " is " + "sqrt", sqrt)
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
When testing it myself, in the beginning, if I entered any other input rather than 1, 2, or 3, it would jump to the "next_calculation" function. I want it to say "That's not an option, silly." instead.
When I select 1 or 3 if I enter anything other than a number the program will stop. I want it to say "That's not a valid number, silly."
How do I do this?
You can do that with continue to ignore the loop and return to the start after checking if the input is in your list of possible values
if choice not in ('1', '2', '3'):
print("Invalid input")
continue
Put that after the input
I'd add right after choice = input("Enter choice(1/2/3): "), this snippet:
while (choice not in ['1','2','3']):
print("That's not a valid number, silly.")
choice = input("Enter choice(1/2/3): ")
In this way, you won't reach the end of the cycle unless you give a correct number.
I think you should try to use Switch in this case, instead of if/elses.
Check out this answer.
Otherwise, #Icenore answer seems to be correct. Also, remember to correctly ident your code, your current else: code is being executed after your while True:
This is my first Python program where I've used if, while and functions. I've also passed parameters. The problem is the IF. Can you help me? I wanted the program to give the user two tries to answer and then end. If correct then it ends but if not correct it doesn't stop, keeps looping.
"""this is a quiz on computer science"""
q1Answer="c"
def questionOne():
print("Here is a quiz to test your knowledge of computer science...")
print()
print("Question 1")
print("What type of algorithm is insertion?")
print()
print("a....searching algorithm")
print("b....decomposition ")
print("c....sorting algorithm ")
print()
def checkAnswer1(q1Answer): #q1Answer is a global variable and is needed for this function so it goes here as a parameter
attempt=0 #These are local variables
score=0
answer = input("Make your choice >>>> ")
while attempt <1:
if answer==q1Answer:
attempt= attempt+1
print("Correct!")
score =score + 2
break
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
else:
print("That is not correct\nThe answer is "+q1Answer )
score =0
return score # This is returned so that it can be used in other parts of the program
##def questionTwo():
## print("Question 2\nWhat is abstraction\n\na....looking for problems\nb....removing irrelevant data\nc....solving the problem\n")
def main():
q1answer = questionOne()
score = checkAnswer1(q1Answer)
print ("Your final score is ", score)
main()
The problem is you aren't incrementing the attempt if they get it wrong the second time. You need another attempt = attempt + 1 (Or alternatively attempt += 1) after the break
So your elif block would look like:
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
attempt = attempt + 1
This allows the attempt counter to increment even if they fail the second time, tiggering the fail and end of loop.
You just add attempt +=1 after the loops.
q1Answer="c"
def questionOne():
print("Here is a quiz to test your knowledge of computer science...")
print()
print("Question 1")
print("What type of algorithm is insertion?")
print()
print("a....searching algorithm")
print("b....decomposition ")
print("c....sorting algorithm ")
print()
def checkAnswer1(q1Answer): #q1Answer is a global variable and is needed for this function so it goes here as a parameter
attempt=0 #These are local variables
score=0
answer = input("Make your choice >>>> ")
while attempt <1:
if answer==q1Answer:
attempt= attempt+1
print("Correct!")
score =score + 2
break
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
else:
print("That is not correct\nThe answer is "+q1Answer )
score =0
attempt += 1
break
return score # This is returned so that it can be used in other parts of the program
##def questionTwo():
## print("Question 2\nWhat is abstraction\n\na....looking for problems\nb....removing irrelevant data\nc....solving the problem\n")
def main():
q1answer = questionOne()
score = checkAnswer1(q1Answer)
print ("Your final score is ", score)
main()
How would I assign the list of operators so that the random numbers are worked out to tell the user if they're correct or not?
# Controlled Assessment - Basic Times Table Test
import random
score = 0
print ("Welcome to the times table test")
name = input("Please type your name: ")
print ("How to play")
print ("Step 1: When you see a question work out the answer and type it in the space.")
print ("Step 2: Once you have typed your answer press the enter key.")
print ("Step 3: The program will tell you if you're right or wrong.")
print ("Step 4: The next question will load and you can repeat from step 1.")
print ("When you have answered all 10 questions your final score will be printed.")
for q in range(10):
Number1 = random.randint(1,12)
Number2 = random.randint(1,12)
ListOfOperator = ['+','-','*']
Operator =random.choice(ListOfOperator)
print ('what is' ,Number1,Operator,Number2)
Answer= input ("Please Type Your Answer: ")
realanswer = (Number1,Operator,Number2)
if ListOfOperator:
ListOfOperator=['+'] = Number1+Number2
ListOfOperator=['-'] = Number1-Number2
ListOfOperator=['*'] = Number1*Number2
if Answer==realanswer:
print("Your answer is correct")
score = score + 1
print (score)
else:
print("Your answer is incorrect, the correct answer is.",realanswer,".")
print (score)
The code that needs to assign to the list of operators is...
if ListOfOperator:
ListOfOperator=['+'] = Number1+Number2
ListOfOperator=['-'] = Number1-Number2
ListOfOperator=['*'] = Number1*Number2
It should work out the answer to each question using the function I'm telling the program that if the operator from the operator list is * to work out Number1*Number2
The current output for telling them if the answer is correct or not prints
Your answer is incorrect, the correct answer is Number1*Number2.
when if the question is what is 10*3 it should be printing
Your answer is incorrect, the correct answer is 30.
Now that I have this code...
if Operator == '+':
realanswer = Number1+Number2
elif Operator == '-':
realanswer = Number1-Number2
elif Operator == '*':
realanswer = Number1*Number2
if Answer==realanswer:
print("Your answer is correct")
score = score + 1
print (score)
else:
print("Your answer is incorrect, the correct answer is.",realanswer,".")
print (score)
The program always prints that the question is incorrect even with the correct answer inputted, it will then print the correct answer, how would I make it so that It would tell them if it's correct too?
The operator module implements basic operations as functions. Define a dict that maps operator symbols such as "+" to the operator function then use that map to do the calculation.
import random
import operator
op_map = {'+':operator.add, '-':operator.sub, '*':operator.mul}
op_list = list(op_map.keys())
score = 0
print ("Welcome to the times table test")
name = input("Please type your name: ")
print ("How to play")
print ("Step 1: When you see a question work out the answer and type it in the space.")
print ("Step 2: Once you have typed your answer press the enter key.")
print ("Step 3: The program will tell you if you're right or wrong.")
print ("Step 4: The next question will load and you can repeat from step 1.")
print ("When you have answered all 10 questions your final score will be printed.")
for q in range(10):
Number1 = random.randint(1,12)
Number2 = random.randint(1,12)
Operator =random.choice(op_list)
print ('what is' ,Number1,Operator,Number2)
while True:
try:
Answer= int(input("Please Type Your Answer: "))
break
except ValueError:
print("Must be an integer... try again...")
realanswer = op_map[Operator](Number1, Number2)
if Answer==realanswer:
print("Your answer is correct")
score = score + 1
print (score)
else:
print("Your answer is incorrect, the correct answer is.",realanswer,".")
print (score)
To perform multiple check like this you can use if, elif statements:
if Operator == '+':
realanswer = Number1+Number2
elif Operator == '-':
realanswer = Number1-Number2
elif Operator == '*':
realanswer = Number1*Number2
For your reference: Python Docs
...
def realanswer(Num1, Op, Num2):
return {
'+': Num1 + Num2,
'-': Num1 - Num2,
'*': Num1 * Num2,
}[Op]
for q in range(2):
Number1 = random.randint(1,12)
Number2 = random.randint(1,12)
ListOfOperator = ['+','-','*']
Operator =random.choice(ListOfOperator)
print ('what is',Number1,Operator,Number2)
userInput = input("Please Type Your Answer: ")
Answer = 0
try:
Answer = int(userInput)
except ValueError:
print("Input not convertible to int!")
rAnswer = realanswer(Number1,Operator,Number2)
if Answer == rAnswer:
print("Correct!")
else:
print("Incorrect...")
I'm writing a Python math game in which the program asks an addition question and the user has to get the right answer to continue. My question is, how can I make the program generate a new math problem when the user gets the last one correct?
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 (True) :
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print("Wrong\n")
userAnswer = int(input("Your answer : "))
input("\n\n Press to exit")
Implement the game with a pair of nested loops. In the outer loop, generate a new arithmetic problem. In the inner loop, keep asking the user for guesses until he either gives the right answer or decides to quit by entering a blank line.
import random
playing = True
while playing:
# Generate a new arithmetic problem.
a = random.randint(1, 50)
b = random.randint(1, 50)
solution = a + b
print('\nWhat is %d + %d? (to quit, enter nothing)' % (a, b))
# Keep reading input until the reply is empty (to quit) or the right answer.
while True:
reply = input()
if reply.strip() == '':
playing = False
break
if int(reply) == solution:
print('Correct. Good job!')
break
else:
print('Wrong. Try again.')
print('Thank you for playing. Goodbye!')
This should get you started. The getnumbers() returns two random numbers, just like in your script. Now just add in you game code. Let me know if you have questions!
import random
def getnumbers():
a = random.randint(1, 50)
b = random.randint(1, 50)
return a, b
print("Math Game!")
while True:
a, b = getnumbers()
# game code goes here
print("%d %d" % (a, b))
input()
This might do what you want:
import random
def make_game():
firstNumber = random.randint(1, 50)
secondNumber = random.randint(1, 50)
result = firstNumber + secondNumber
result = int(result)
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
userAnswer = int(input("Your answer : "))
while (True) :
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print("Wrong\n")
userAnswer = int(input("Your answer : "))
print("Hello ! What\'s your name ? ")
name = input()
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
while True:
make_game()
end = input('\n\n Press to "end" to exit or "enter" to continue: ')
if end.strip() == 'end':
break
def multiply(): #starts sub program when 'multiply()' is called
num1 = random.randint(1,12) #randomly generates a number between 1 and 12
num2 = random.randint(1,12)
while loop == True: #creates loop, and uses previously defined 'loop'
ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? ")) #asks question and requires a user input
correct = (ans == num1 * num2)
if correct:
print("You are correct! ")
break #if the answer is correct, it prints 'You are correct!' and breaks to avoid the loop
else:
print("Wrong, please try again. ")
loop == False #if the answer is wrong, it loops back to when 'loop' was last 'True'
I am wondering if there is a way for me to include a line of code that allows me to display "That is not an option!" when a symbol other than a number is entered into the 5th line in the code.
Use an exception to catch unexpected inputs.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
def multiply():
# Randomly generates a number between 1 and 12
num1 = random.randint(1,12)
num2 = random.randint(1,12)
while True:
i = input("What is the answer to {} x {} ".format(
str(num1), str(num2)))
try:
ans = int(i)
except ValueError:
print('That is not an option!')
continue
if ans == num1 * num2:
print("You are correct!")
break
else:
print("Wrong, please try again.")
if __name__ == "__main__":
multiply()
When you convert to int there is the chance that they will enter a non-integer value so the conversion will fail, so you can use a try/except
def multiply(): #starts sub program when 'multiply()' is called
num1 = random.randint(1,12) #randomly generates a number between 1 and 12
num2 = random.randint(1,12)
while loop == True: #creates loop, and uses previously defined 'loop'
try:
ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? ")) #asks question and requires a user input
correct = (ans == num1 * num2)
if correct:
print("You are correct! ")
break #if the answer is correct, it prints 'You are correct!' and breaks to avoid the loop
else:
print("Wrong, please try again. ")
loop == False
except ValueError:
print("That is not an option")
Note that your previous code is now nested in a try block. If the int() fails because they entered a bad input, it will throw a ValueError that you can catch and notify them.
As a side note, another way to format your question to them would be
'What is the answer to {} x {}?'.format(num1, num2)
This is a nice way to generate a string with injected variable values.