my program keeps returning a score of 0 everytime I run it even with the corrcect answer. Also how would I go about subtractiong points for a wrong answer.
P.S, This is my first time coding anything.
score = 0
print('Math Quiz')
def check_answer(question, answer):
global score
if question == answer:
print("Correct answer!")
score = score + 1
else:
print('Sorry, wrong answer.')
question_1 = input('What is 2 times 2?\n')
check_answer(question_1, 4)
question_2 = input('What is 1 minus 1?\n')
check_answer(question_2, 0)
question_3 = input('What is 4 divided by 2?\n')
check_answer(question_3, 2)
question_4 = input('What is 3 to the third power?\n')
check_answer(question_4, 9)
question_5 = input('What is 3 times 5?\n')
check_answer(question_5, 15)
print(score)
The problem is, that input() returns a string which leads to an incompatible comparison of your data types. You could solve this by creating an integer with the value of your input like this: question_1 = int(input('What is 2 times 2?\n'))
the other problem could be solved by decreasing the score in your else block
input('') returns a string and you are comparing it to a int.
check_anser(int(question_2),0)
or comparte to string version of the numbers
check_anser(question_2,"0")
Related
Looking on for some guidance on how to write a python code
that executes the following:
The program will ask for math problems to solve.
The program will asks for the number of problems.
And asks for how many attempts for each problem.
For example:
Enter amount of programs: 4
Enter amount of attempts: 5
what is: 4x3 =?
Your answer: 16
and so goes on to another attempt if wrong if correct moves onto another problem, just like before and exits when attempts or problems are finished.
I have this code but I want to it only do multiplication ONLY and would like to know how to integrate how to put additional code to limit how many time one can solve the question and how many questions it asks
import random
def display_separator():
print("-" * 24)
def get_user_input():
user_input = int(input("Enter your choice: "))
while user_input > 5 or user_input <= 0:
print("Invalid menu option.")
user_input = int(input("Please try again: "))
else:
return user_input
def get_user_solution(problem):
print("Enter your answer")
print(problem, end="")
result = int(input(" = "))
return result
def check_solution(user_solution, solution, count):
if user_solution == solution:
count = count + 1
print("Correct.")
return count
else:
print("Incorrect.")
return count
def menu_option(index, count):
number_one = random.randrange(1, 21)
number_two = random.randrange(1, 21)
problem = str(number_one) + " + " + str(number_two)
solution = number_one + number_two
user_solution = get_user_solution(problem)
count = check_solution(user_solution, solution, count)
def display_result(total, correct):
if total > 0:
result = correct / total
percentage = round((result * 100), 2)
if total == 0:
percentage = 0
print("You answered", total, "questions with", correct, "correct.")
print("Your score is ", percentage, "%. Thank you.", sep = "")
def main():
display_separator()
option = get_user_input()
total = 0
correct = 0
while option != 5:
total = total + 1
correct = menu_option(option, correct)
option = get_user_input()
print("Exit the quiz.")
display_separator()
display_result(total, correct)
main()
As far as making sure you're only allowing multiplication problems, the following function should work.
def valid_equation(user_input):
valid = True
for char in user_input:
if not(char.isnumeric() or char == "*"):
valid = False
return valid
Then after each user_input you can run this function and it will return True if the only things in the users string are numbers and the * sign and False otherwise. Then you just need to check the return value with a if statement that tells the user that their input is invalid if it returns False. You can add more "or" operations to the if statement if you want to allow other things. Like if you want to allow spaces (or char == " ").
As far as limiting the number of times a user can try to answer, and limiting the number of questions asked, you just need to store the values the user enters when you ask them these numbers. From there you can do nested while loops for the main game.
i = 0
user_failed = False
while ((i < number_of_questions) and (user_failed == False)):
j = 0
while ((j < number_of_attempts) and (user_correct == False)):
#Insert question asking code here
#In this case if the user is correct it would make user_correct = True.
j += 1
if j == number_of_attempts:
user_failed = True
i += 1
So in this situation, the outer while loop will iterate until all of the questions have been asked, or the user has failed the game. The inner loop will iterate until the user has used up all of their attempts for the question, or the user has passed the question. If the loop exits because the user used up all of their attempts, the for loop will trigger making the user lose and causing the outer loop to stop executing. If it does not it will add one to i, saying that another question has been asked, and continue.
These are just some ideas on how to solve the kinds of problems you're asking about. I'll leave the decision on how exactly to implement something like this into your code, or if you decide to change parts of your code to better facilitate systems like this up to you. Hope this helps and have a great one!
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am trying to create a simple guessing game. Everything works absolutely fine, as it should. But, it can't seem to exit the first while loop which checks if the variable 'guessflag' is less than 15 or not. I also checked whether it is being updated or not by adding some print statements. Please help.
It even exits when it meets the condition which says to exit the program when the user guesses correctly. When I consulted some other queries regarding the same problem at stackoverflow, I tried to make sure that those mistakes don't happen to me. Also, I have to add some more finishing touches to reduce time taken by the program to run, but currently this works absolutely fine.
import random
point = 101
randomint = random.randint(0,100)
hintflag = 0
hintmessage = "To claim a hint, enter 102 in the input below. ***THE HINT WILL COME AT A COST OF 20 POINTS***"
guessflag = 0
while guessflag <=15:
def init(param):
global guess, point, guessflag
if(param == 1):
global point,guessflag
point = point - 1
guessflag = guessflag + 1
print(hintmessage)
guess = int(input("Enter your guess. It should be between 1 and 100... "))
proceed()
def proceed():
global hintflag
global point
if (guess < 1 or (guess > 100 and guess != 102)):
print('')
print("Please enter a number between 1 and 100... ")
init(2)
elif ((guess == 102)and(hintflag < 2 and hintflag >= 0)):
if(hintflag == 0):
checkrandeven()
if(hintflag == 1):
checkrandmultiple3()
else:
match()
def checkrandmultiple3():
if (randomint % 3 == 0):
global israndmultiple3, point, hintmessage, hintflag
hintflag = hintflag + 1
israndmultiple3 = True
point = point-20
hintmessage = 'You have exhausted all your hints'
print("The number to be guessed is a multiple of 3.")
print("Points: "+str(point))
init(2)
else:
hintflag = hintflag+1
israndmultiple3 = False
point = point-20
hintmessage = 'You have exhausted all your hints'
print("The number to be guessed is not a multiple of 3.")
print("Points: "+str(point))
init(2)
def checkrandeven():
if (randomint % 2 == 0):
global israndeven, point, hintmessage, hintflag
hintflag = hintflag+1
israndeven = True
point = point-20
hintmessage = 'To claim your ***LAST*** hint, enter 102 in the input below. ***THE HINT WILL COME AT A COST OF 20 POINTS***'
print('')
print("Your hint is...")
print("The number to be guessed is even.")
print("***YOU HAVE SPENT 20 POINTS***")
print("Points: "+str(point))
init(2)
else:
israndeven = False
hintflag = hintflag+1
point = point-20
hintmessage = 'To claim your ***LAST*** hint, enter 102 in the input below. ***THE HINT WILL COME AT A COST OF 20 POINTS***'
print("The number to be guessed is odd.")
print("Points: "+str(point))
init(2)
def match():
global randomint, guess, point, guessflag, hintflag
if(randomint != guess):
if(randomint < guess):
print("Try Again! Your number was too high; Try a number lower than "+str(guess))
init(1)
if(randomint > guess):
print("Try Again! Your number was too low; Try a number higher than "+str(guess))
init(1)
if(randomint == guess):
print ("CONGRATULATIONS! You won!")
print ("It took you "+ str(guessflag) + " tries, "+ str(hintflag)+" hints to beat the game!")
print("The number of points you finished with are... "+ str(point))
exit()
init(1)
The 'init(1)' call in your while loop is only actually called once, and your 4 functions call each other recursively. In other words, you never actually finish the first iteration of your while loop, you just go further and further down a chain of:
init -> proceed -> checkrandeven (or checkrandmultiple3) -> init -> proceed -> checkrandeven -> init -> proceed ...
Basically you need to think about restructuring your code to avoid the recursion. Try returning outputs within the main loop and then calling subsequent functions from there.
In my program it's supposed to ask the user a question and give them 3 chances to guess the correct answer. But my "while" loop seems to give the user a 4th chance to answer the question and bypassing the "max_attempts" variable.
print('Quiz program!\n')
answer = input('What is the capital of Wisconsin? ')
attempt = 1
max_attempts = 4
while answer != 'Madison':
attempt += 1
print('You got it wrong, please try again.\n')
answer = input('What is the capital of Wisconsin? ')
if attempt == max_attempts:
print('You used the maximum number of attempts, sorry. The correct answer is "Madison"')
break
else:
print(f"Correct! Thanks for playing. It took you {attempt} attempt(s).")
All the above answers are correct, just adding a slightly different variant.
print('Quiz program!\n')
attempt = 1
max_attempts = 4
while attempt < max_attempts:
attempt += 1
answer = input('What is the capital of Wisconsin? ')
if answer == 'Madison':
print("Correct!")
break
else:
print('You got it wrong, please try again.\n')
print("Thanks for playing. It took you %s attempt(s)." %(attempt-1))
You have max_attempts = 4 - change that to 3.
You should check if the counter attempt attempt is equal to max_attempts at the beginning of the loop, before you increment the counter again, and you should set max_attempt to 3 instead:
print('Quiz program!\n')
answer = input('What is the capital of Wisconsin? ')
attempt = 1
max_attempts = 3
while answer != 'Madison':
if attempt == max_attempts:
print('You used the maximum number of attempts, sorry. The correct answer is "Madison"')
break
attempt += 1
print('You got it wrong, please try again.\n')
answer = input('What is the capital of Wisconsin? ')
else:
print(f"Correct! Thanks for playing. It took you {attempt} attempt(s).")
The problem is with your condition. It should be
attempt < max_attempts:
I also tried implementing it in a more readable way
def main():
introduction()
attempt=1
while attemptValid(attempt) and answerIsWrong(askQuestion(), attempt):
attempt += 1
def attemptValid(attempt):
max_attempts=4
if attempt < max_attempts:
return 1
print('You used the maximum number of attempts, sorry. The correct answer is "Madison"')
return 0
def answerIsWrong(answer, attempt):
if answer != 'Madison':
return 1
print(f"Correct! Thanks for playing. It took you {attempt} attempt(s).")
return 0
def introduction():
print('Quiz program!\n')
def askQuestion():
return input('What is the capital of Wisconsin? ')
main()
Surely, by adjusting the variable max_attempts to 2, 3, 4, 5 you will eventually find the right number to give you the correct behaviour. But I believe it is more important to know how to think of this issue. I would suggest to think in terms of loop invariants: Make up a condition that is always true in the loop and enforce it while you write the loop. In this case, let's make the value of attempt and the number of time of input() calls equal, and see if your loop is right:
print('Quiz program!\n')
answer = input('What is the capital of Wisconsin? ')
attempt = 1
max_attempts = 4
So your attempt set to 1 after input(). This part is OK, and satisfied the invariant (even it is before the loop). Then the loop:
while answer != 'Madison':
attempt += 1
print('You got it wrong, please try again.\n')
answer = input('What is the capital of Wisconsin? ')
if attempt == max_attempts:
print('You used the maximum number of attempts, sorry. The correct answer is "Madison"')
break
You increment attempt, then print, then call input(). I will put the attempt line right after input() call to be consistent with the code above but either case, at right before the if statement, we still have value of attempt equals to number of times we called input(). That is why you have this behaviour.
Now on how to change your code: you now knows what is "invariant" in the loop. You have to decide (1) when to do the check of attempt == max_attempts and (2) what is the right value of max_attempts to check. Other people's answer already gave you the solution.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
sorry, does anyone know why this program doesn't work? I'm very new to python (as you can see from my inefficient programming), and I can't think of any reason why this souldn't work. Please help. Thankyou!
#Land Game Calculator
game = 1
hamlet = 0
village = 0
town = 0
city = 0
capital = 0
palace = 0
farm = 0
factory = 0
ruins = 0
apolw = 0
apoll = 0
polw = 0
poll = 0
squaresused = hamlet+village+town+city+capital+palace+farm+factory+ruins+apolw+apoll+polw+poll
income = hamlet+(village*2)+(town*3)+(city*4)+(capital*5)+(palace*6)+farm+(factory*3)
while game == 1:
if input("What would you like to do? ") == hamlet:
hamlet = hamlet+(int(input("How many would you like to add? ")))
print("There are now "+str(hamlet)+" of them")
elif input("What would you like to do? ") == village:
village = village+(int(input("How many would you like to add? ")))
print("There are now "+str(village)+" of them")
elif input("What would you like to do? ") == town:
town = town+(int(input("How many would you like to add? ")))
print("There are now "+str(village)+" of them")
The problem is that you're comparing strings with integers.
This lies in the input lines:
if input("What would you like to do? ") == hamlet:
Here, hamlet is an int, defined as hamlet = 0.
On the other hand, input() returns a str.
The value returned by input will never be equal to hamlet.
What you mean to do is, I presume, trigger a different action according to what the user typed in.
I guess you expect the user to type either "hamlet", "village", or "town".
Therefore, the comparison should be on those strings rather on the variables:
if input("What would you like to do? ") == "hamlet":
The while loop wasn't working properly, but it's fixed by changing from calling an if input... within each paragraph
command = ""
game = 1
while game == 1:
game = 1
command = input("What would you like to do? ")
if command == hamlet:
hamlet = hamlet+(int(input("How many would you like to add? ")))
print("There are now "+str(hamlet)+" of them")
game = 1
elif command == village:
game = 1
village = village+(int(input("How many would you like to add? ")))
print("There are now "+str(village)+" of them")
game = 1
I am creating a maths quiz in python. I have made the code so that 10 random questions are being asked. At the end of the quiz it should tell the user the quiz has finished and how much they scored in the quiz but I'm having some difficulty in that. Here is a section of my code where I believe I have gone wrong:
def askquestion():
score = 0
opslist = {operator.add: "+", operator.sub: "-", operator.mul: "x"} #All operators that can be chosen
num1,num2 = random.randint(1,10), random.randint(1,10) #Two Random Numbers
ops = random.choice(list(opslist.keys())) # random operators from oplist keys
ActualAnswer = (ops(num1,num2)) #Answer for my quiz
score = 0
print(num1,opslist[ops],num2) # Question for my quiz
userAns = (int(input("Enter answer:")))
if userAns == ActualAnswer: #If the user's answer matches the Actual Answer
print("Correct")
score = score + 1
else:
print("Incorrect")
score = score - 0
for i in range (10):
askquestion()
print ("The quiz has finished")
print ("Today you achieved a score of" ,score,"out of 10")
Say I move the for loop below the last print so that it is not part of the def askquestion(): I get an output like this:
2 + 6
Enter answer:8
Correct
The quiz has finished
Today you achieved a score of 1 out of 10
6 x 3
Enter answer:18
Correct
The quiz has finished
Today you achieved a score of 1 out of 10
5 x 1
Enter answer:5
Correct
The quiz has finished
Today you achieved a score of 1 out of 10
If I keep it in the position it is along with the rest of the code it just doesn't ask me the questions and the program stops after the introduction where the program asks for the name. If you think you need the rest of the code please provide an e-mail address but I am positive I've gone wrong in the code provided.
Q.) What should I change so that when the 10 questions are over the score is outputted at the end
There were a few problems in your code. Here's is what I came up with to fix it.
import operator
import random
def askquestion():
score = 0
opslist = {operator.add: "+", operator.sub: "-", operator.mul: "x"} #All operators that can be chosen
num1,num2 = random.randint(1,10), random.randint(1,10) #Two Random Numbers
ops = random.choice(list(opslist.keys())) # random operators from oplist keys
ActualAnswer = (ops(num1,num2)) #Answer for my quiz
score = 0
print(num1,opslist[ops],num2) # Question for my quiz
userAns = (int(input("Enter answer:")))
if userAns == ActualAnswer: #If the user's answer matches the Actual Answer
print("Correct")
return 1
else:
print("Incorrect")
score = score - 0
return 0
totalScore = 0
for i in range (10):
totalScore += askquestion()
print ("The quiz has finished")
print ("Today you achieved a score of" ,totalScore,"out of 10")
All of your askQuestion() function is good, but variables in functions aren't global, so you need to return it to use it later. Instead of having to keep track of the variable created in the function, you can use a global variable totalScore to keep track of the score. askQuestion() now returns a 1 when the answer is right and a 0 if the answer is wrong.
Now you need to move the for loop out of askQuestion() so it works. The for i in range(10): works but you could also use a while loop like this:
totalScore = 0
i = 0
while i < 10:
totalScore += askQuestion()
i += 1
In the loop, you are using the global variable totalScore to keep track of the 1's and 0's return by askQuestion(). At the end, you are just printing the score.
You need to put your if/else blocks inside your askquestion() function or after it in the for loop
Broadly speaking you want something like this
def ask_question():
#your question logic here
#increment score
def print_summary(score):
print "Today you got a score of..."
for i in range(10):
ask_question()
print_summary()
Define functions that perform each task in your program then indicate the order your program should flow through those functions.
What you really want to do is encapsulate the quiz logic in a class with ask question, administer quiz and print summary methids .