Always Says Its The Wrong Answer? - python

I'm making a simple maths quiz its working fine except when I ask if its the correct answer it always says Incorrect if its correct or not. I'm not sure where I went wrong any help on this would be appreciated.
import random
QuestN = 1
QNC = 0
CS = 0
WS = 0
while True:
#Number Of Questions:
QNC = QNC + 1
if QNC == 10:
break
#Choosing The Questions
ops = ['+', '-', '*', '/']
num1 = random.randint(0,12)
num2 = random.randint(1,10)
operation = random.choice(ops)
#Simplifying The Operations
if operation == "+":
NEWOP = "+"
elif operation == "-":
NEWOP = "-"
elif operation == "*":
NEWOP = "x"
elif operation == "/":
NEWOP = "รท"
#Asking The Questions
print("Awnser This:")
print(num1)
print(NEWOP)
print(num2)
maths = eval(str(num1) + operation + str(num2))
#Awnsering The Questions
PLAYERA = input(": ")
print(maths)
#Keeping Score
if PLAYERA == maths:
print("Correct")
CS = CS +1
else:
print("Incorrect")
WS = WS +1
print()
#RESTART

The variable PLAYERA will be a string. The variable maths will be an integer. In Python, "7" isn't the same thing as 7, so your if statement will never be true.
You therefore need to this:
if int(PLAYERA) == maths:
print("Correct")
CS = CS +1
Note that this code will cause an error it the player's input isn't a number. You could avoid that by doing this instead:
if PLAYERA == str(maths):
print("Correct")
CS = CS +1

Related

Implementing a timer into Math game in Python

import random
from tkinter import *
import tkinter as tk
import time
scores = []
score = 0
#introduction
def start():
print(" Welcome to Maths Smash \n")
print("Complete the questions the quickest to get a better score\n")
username = True #this makes sure the user can only enter characters a-z
while username:
name = input("What is your name? ")
if not name.isalpha():
print("Please enter letters only")
username = True
else:
print("Ok,", name, "let's begin!")
main()
#menu
def main():
choice = None
while choice !="0":
print(
"""
Maths Smash
0 - Exit
1 - Easy
2 - Medium
3 - Hard
4 - Extreme
5 - Dashboard
"""
)
choice = input("Choice: ")
print()
#exit
if choice == "0":
print("Good-bye!")
quit()
#easy
elif choice == "1":
print("Easy Level")
easy_level()
#medium
elif choice == "2":
print("Medium Level")
medium_level()
#hard
elif choice == "3":
print("Hard Level")
hard_level()
#extreme
elif choice == "4":
print("Extreme Level")
extreme_level()
#teacher login
elif choice == "5":
print("Dashboard")
from GUI import dashboard
dashboard()
else:
print("Sorry but", choice, "isn't a vaild choice.")
def easy_level():
global score
#easy level
for i in range(10):
operator_sign =""
answer = 0
num1 = random.randint(1,5)
num2 = random.randint(1,5)
operator = random.randint(1,4)
#choosing the operator randomly
if operator == 1:
operator_sign = " + "
answer = num1 + num2
elif operator == 2:
operator_sign = " - "
answer = num1 - num2
elif operator == 3:
operator_sign = " * "
answer = num1 * num2
elif operator == 4:
operator_sign = " / "
num1 = random.randint(1,5) * num2
num2 = random.randint(1,5)
answer = num1 // num2
else:
print("That is not a vaild entry!\n")
#outputting the questions along with working out if it's correct
question = str(num1) + operator_sign + str(num2) + "\n"
user_input = int(input(question))
if user_input == answer:
score = score + 1
#total score
print("You scored:", str(score), "out of 10")
Been trying to add a timer in this game for a while but every time I go to the first level it doesn't work with the game at the same time, as in I will load the first level and none of the questions will pop-up until the timer has completed. Was wondering if anyone could help me or know a fix to this, I want to make it so if the user completes the test within a certain amount of time they get an additional 10 points added to the overall score. This is what I had come up with at first:
def timer():
countdown=120
while countdown >0:
time.sleep(1)
score = score + 10

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")

What does getting a string index out of range error mean?

I am making a calculator in python 3, and I made a function to check for letters in the input. When it runs the letter check though, it gives me an error of string index out of range. Here is the code:
while True:
num = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
op = input("What operation would you like to use(+,-,*,/,**): ")
num1 = input("What is the first number you want to use: ")
length1 = len(num1)
lc1 = 0
def letterCheck1():
global num1
global length1
global lc1
while lc1 <= length1:
if num1[lc1] in num:
num1 = input("No letters, just numbers: ")
else:
lc1 = lc1 + 1
while True:
letterCheck1()
if len(num1) == 0:
num1 = input("Actually enter something: ")
continue
else:
break
num2 = input ("What is the second number you want to use: ")
length2 = len(num2)
lc2 = 0
def letterCheck2():
global num2
global length2
global lc2
while lc2 <= length2:
if num2[lc2] in num:
num2 = input("No letters, just numbers: ")
else:
lc2 = lc2 + 1
while True:
while True:
if op == "/" and num2 == "0":
num2 = input("It is impossible to divide a number by 0. Try again: ")
continue
else:
break
letterCheck2()
if len(num2) == 0:
num2 = input("Enter more than 0 numbers please: ")
continue
else:
break
if op == "+":
print (float(num1) + float(num2))
elif op == "-":
print (float(num1) - float(num2))
elif op == "*":
print (float(num1) * float(num2))
elif op == "/":
print (float(num1) / float(num2))
elif op == "**":
print (float(num1) ** float(num2))
again = input("Would you like to do another problem? 1(Yes), 2(No): ")
while True:
if again != "1" or again != "2":
again = input("Please enter 1(Yes), or 2(No): ")
continue
else:
break
if again == "1":
continue
elif again == "2":
leave = input("You are about to exit, do you want to continue? 1(Yes), 2(No): ")
while True:
if leave != ("1" or "2"):
leave = input("Please enter 1(Yes), or 2(No): ")
continue
else:
break
if leave == '1':
continue
elif leave == '2':
break
Indexing from 0 to len(num1) - 1. Fix this
while lc1 < length1
and this
while lc2 < length2
Here is a much cleaner way to do it:
def get_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
# not a float, try again
pass
# division is the only operation that requires more than a one-liner
def op_div(a, b):
if b == 0:
print("Dividing by 0 makes the universe explode. Don't do that!")
return None
else:
return a / b
# dispatch table - look up a string to get the corresponding function
ops = {
'*': lambda a,b: a * b,
'/': op_div,
'+': lambda a,b: a + b,
'-': lambda a,b: a - b,
'**': lambda a,b: a ** b
}
def main():
while True:
op = input("What operation would you like to use? [+, -, *, /, **, q to quit] ").strip().lower()
if op == "q":
print("Goodbye!")
break
elif op not in ops:
print("I don't know that operation")
else:
a = get_float("Enter the first number: ")
b = get_float("Enter the second number: ")
res = ops[op](a, b)
print("{} {} {} = {}".format(a, op, b, res))
if __name__=="__main__":
main()

how do i make my python code work? random math quiz

This is my code it has to have + - * in the code and it has to be chosen randomly but it does not work it does not say the correct answer I would appreciate any help thanks.
import random
import operator
question_number = 0
score = 0
ops = {'+':operator.add,
'-':operator.sub,
'*':operator.mul,
'/':operator.truediv}
number1 = random.randint(0,12)
number2 = random.randint(1,10)
op = random.choice(list(ops.keys()))
print ("this is a short maths quiz")
name = input ("what is your name")
age = input ("how old are you " +name)
print ("ok "+name+" im going to start the quiz now")
print(number1, op, number2)
user_input=int(input())
answer = (number1,op,number2)
if user_input == answer:
print("Well done")
score = score + 1
else:
print("WRONG!")
print("The answer was",answer)
question_number = question_number + 1
You need to op as a key to get the appropriate value from the ops dict and call it on the two numbers:
answer = ops[op](number1, number2)
Your code is comparing an int to a tuple i.e 9 == (3, '+', 6)
You may also want to keep the larger number on the left and smaller on the right unless you want negative numbers.
answer = ops[op](max(number1,number2),min(number1, number2))
Also unless this is in a while loop question_number = question_number + 1 is not going to do much.
you need to make the op an op and not a string.
this is your code fixed.
import random
import operator
question_number = 0
score = 0
ops = {'+':operator.add,
'-':operator.sub,
'*':operator.mul,
'/':operator.truediv}
number1 = random.randint(0,12)
number2 = random.randint(1,10)
op = random.choice(list(ops.keys()))
print ("this is a short maths quiz")
name = input ("what is your name")
age = input ("how old are you " +name)
print ("ok "+name+" im going to start the quiz now")
print(number1, op, number2)
user_input=int(input())
if op == "+":
answer = (number1+number2)
elif op == "-":
answer = (number1-number2)
elif op == "*":
answer = (number1*number2)
elif op == "/":
answer = (number1/number2)
if user_input == answer:
print("Well done")
score = score + 1
else:
print("WRONG!")
print("The answer was",answer)
question_number = question_number + 1
you could add a while loop to make it repeating

python - ask random mathematical questions not quite working

I need help with this program that I'm writing. It asks random mathematical questions. It chooses between +, - and x. Here's my code
import random
def questions():
name=input("What is your name: ")
print("Hello there",name,"!")
choice = random.choice("+-x")
finish = False
questionnumber = 0
correctquestions = 0
while finish == False:
if questionnumber < 10 | questionnumber >= 0:
number1 = random.randrange(1,10)
number2 = random.randrange(1,10)
print((number1),(choice),(number2))
answer=int(input("What is the answer?"))
questionnumber = questionnumber + 1
if choice==("+"):
realanswer = number1+number2
if answer==realanswer:
print("That's the correct answer")
correctquestions = correctquestions + 1
else:
print("Wrong answer, the answer was",realanswer,"!")
if choice==("x"):
realanswer = number1*number2
if answer==realanswer:
print("That's the correct answer")
correctquestions = correctquestions + 1
else:
print("Wrong answer, the answer was",realanswer,"!")
elif choice==("-"):
realanswer = number1-number2
if answer==realanswer:
print("That's the correct answer")
correctquestions = correctquestions + 1
else:
print("Wrong answer, the answer was",realanswer,"!")
else:
finish = True
else:
print("Good job",name,"! You have finished the quiz")
print("You scored " + str(correctquestions) + "/10 questions.")
questions()
The output:
What is your name: s
Hello there s !
6 - 9
What is the answer?-3
That's the correct answer
9 - 8
What is the answer?1
That's the correct answer
9 - 7
What is the answer?2
That's the correct answer
8 - 3
What is the answer?4
Wrong answer, the answer was 5 !
5 - 6
What is the answer?1
Wrong answer, the answer was -1 !
8 - 7
What is the answer?1
That's the correct answer
3 - 5
What is the answer?2
Wrong answer, the answer was -2 !
4 - 5
What is the answer?1
Wrong answer, the answer was -1 !
7 - 2
What is the answer?5
That's the correct answer
7 - 1
What is the answer?6
That's the correct answer
Good job s ! You have finished the quiz
You scored 6/10 questions.
Now the program is running fine but it asks the questions with the same operator (+, -, x) every time I start the program a different operator questions happen but I want to run it so it actually asks different adding, subtracting, multiplication questions inside the program so all the questions that it asks it will be different questions like x, + and - every different question.
It should help if you move the choice part inside the loop:
while not finish: # better than finish == False
choice = random.choice("+-x")
# etc
import random
correct = 0
name = input("Please enter your name: ")
for count in range(10):
num1 = ranom.randint(1, 100)
num2 = radom.randint(1, 100)
symbol = rndom.choice(["+", "-", "*"])
print("Please solve:\n", num1, symbol, num2)
user = int(input(""))
if symbol == "+":
answer = num1 + num2
elif symbol == "-":
answer = num1 - num2
elif symbol == "*":
answer = num1 * num2
if user == answer:
print("Wong u wetard")
correct = correct + 1
else:
print("correct")
print(name, ", You Got", correct, "Out Of 10")
After while finish == false put this !
choice = random.choice("+-x")
I have attempted the same problem that you face, and after looking at your code I made the changes detailed below. the code works and it is (relatively) neat and concise.
def name_enter():
global name
name = ""
while name == "" or len(name) > 25 or not re.match(r'^[A-Za-z0-9-]*$', name):
name = input("Please enter your name: ")
enter_class()
def enter_class():
global class_choice
class_choice = None
while class_choice not in ["1","3","2"]:
class_choice = input("Please enter you class (1, 2, 3): ")
print("\nClass entered was " + class_choice)
mathsquestion()
def mathsquestion():
global qa, score
qa, score = 0, 0
for qa in range(0,10):
qa = qa + 1
print("The question you are currently on is: ", qa)
n1, n2, userans = random.randrange(12), random.randrange(12), ""
opu = random.choice(["-","+","x"])
if opu == "+":
while userans == "" or not re.match(r'^[0-9,-]*$', userans):
userans = input("Please solve this: %d" % (n1) + " + %d" % (n2) + " = ")
prod = n1 + n2
elif opu == "-":
while userans == "" or not re.match(r'^[0-9,-]*$', userans):
userans = input("Please solve this: %d" % (n1) + " - %d" % (n2) + " = ")
prod = n1 - n2
else:
while userans == "" or not re.match(r'^[0-9,-]*$', userans):
userans = input("Please solve this: %d" % (n1) + " x %d" % (n2) + " = ")
prod = n1 * n2
userans = int(userans)
prod = int(prod)
if prod == userans:
score = score + 1
print("Well done, you have got the question correct. Your score is now: %d" % (score))
else:
print("Unfortunatly that is incorrect. The answer you entered was %d" % (userans) + " and the answer is actually %d" % (prod))
print("Your final score is: %d" % (score))
name_enter()
This is a very different code but should do the same thing. It's also much shorter and neater.
import random
correct = 0
name = input("Please enter your name: ")
for count in range(10):
num1 = random.randint(1, 100)
num2 = random.randint(1, 100)
symbol = random.choice(["+", "-", "*"])
print("Please solve:\n", num1, symbol, num2)
user = int(input(""))
if symbol == "+":
answer = num1 + num2
elif symbol == "-":
answer = num1 - num2
elif symbol == "*":
answer = num1 * num2
if user == answer:
print("Correct!")
correct = correct + 1
else:
print("Incorrect")
print(name, ", You Got", correct, "Out Of 10")

Categories

Resources