print("Hello, and welcome to the Maths quiz!/n")
#Asks user for name - 05/03/2015
name = input("What is your name?")
#This will import random to generate random functions
import random
#This is a variable for score
#It has been set to 0 at the start of the program
score = 0
#This creates an array containing the mathematical operators
#that this quiz will use
ops = ['+','-','*']
#A loop has been set for 0 - 10
for x in (0,10):
#This is variable has been set to the operator of the equation that
#uses the random function and will choose a random operator from the
#array containing the operators made earlier
op = random.choice(ops)
if op == '+':
left1 = random.randint(1,100)
right1 = random.randint(1,100)
print (str(left1) + op + str(right1))
answer = eval(str(left1) + op + str(right1))
guess = input("")
if guess == answer:
print("Correct!")
score += 1
else:
print ("Incorrect")
elif op == '-':
left2 = random.randint(1,100)
right2 = random.randint(1,100)
print (str(left2) + op + str(right2))
answer1 = eval(str(left2) + op + str(right2))
guess1 = int(input(""))
if answer1 == guess1:
print("Correct!")
score += 1
else:
print("Incorrect")
elif op == '*':
left3 = random.randint(1,100)
right3 = random.randint(1,100)
print (str(left3) + op + str(right3))
answer2 = eval(str(left3) + op + str(right3))
guess2 = input("")
if answer2 == guess2:
print("Correct!")
score += 1
else:
print("Incorrect")
else:
break
print (score)
When I do this, it generates a random quiz that only loops twice, even though I want it to loop 10 times. Also, it sometimes give the right answer and sometimes the wrong answer. For example:
Hello, and welcome to the Maths quiz!/n
What is your name?j
95*3
285
Incorrect
35-46
-11
Correct!
What I want for this to do is generate random arithmetic questions using the addition, subtraction and multiplication operators. Plus, for it to loop 10 times and give a score out of 10 at the end.
This
for x in (0,10):
...
runs the code (...) two times: one time with x set to 0, and a second time with x set to 10.
What you really want is this:
for x in range(10):
...
Then x will be 0, 1, ..., 9 and the code runs 10 times.
You are not always converting the input to an integer.
When op == '*' or op == '+', you try to compare against the string returned from input():
guess2 = input("")
String comparisons to numbers are never equal. For op == '-' you correctly convert the answer to an integer first:
guess1 = int(input(""))
Your loop is broken too; you are looping over a tuple containing two values:
for x in (0, 10):
rather than over a range:
for x in range(0, 10):
You'd be far better off avoiding so much repetition in your code; calculate the expression outcome and ask for the answer in one place; that way there are fewer places to make mistakes.
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 12 months ago.
I'm a python beginner in and got an assignment for school to make the simple number guessing "game" where you have to figure out a number by guessing and it either says higher or lower until you guess the correct number. It worked well until i added two player support and the ability to choose the interval that the random number will be in. Now the higher/lower result from the guess is the opposite if the amount of digits in the guess is different from the random unkown number. Lets say that the random number is 50, then guessing a number between 10-49 will give the result "guess higher", guessing a number between 99-51 will give the result "guess lower" like it's supposed to do. However if the guess is a different amount of digits like 0-9 it will say "guess lower" which is the opposite, same if i guess 100 or anything above it will say "guess higher".
The code:
import random
while True:
select = input("En eller två spelare? ")
if select == '1':
y = input("0 - ")
num = str(random.randint(1, int(y)))
while True:
guess = input('Gissa mellan 0 - ' + y+": ")
if guess == num:
print('Rätt nummer: ' + guess)
break
elif guess == "haks":
print(num)
elif guess < num:
print('Högre än ' + guess)
elif guess > num:
print('Lägre än ' + guess)
if select == '2':
spelare1 = input("Spelare 1: ")
spelare2 = input("Spelare 2: ")
y = input("0 - ")
num = str(random.randint(1, int(y)))
spelare = 0
while True:
if spelare%2 == 0:
print(spelare1 + 's tur')
if spelare%2 == 1:
print(spelare2 +'s tur')
guess = input('Gissa mellan 0 - ' + y+": ")
if guess == num:
print('Rätt nummer: ' + guess)
if spelare%2 == 0:
print(spelare1, "vann!")
break
if spelare%2 == 1:
print(spelare2, "vann!")
break
elif guess == "haks":
print(num)
elif guess < num:
print('Högre än ' + guess)
spelare = spelare+1
elif guess > num:
print('Lägre än ' + guess)
spelare = spelare+1
I can't find any logic in this and already spent to much time on trying to fix it. Any help is much appreciated and if there are any questions about the code I'll happily answer them.
The number of digits doesn't matter
There's a difference between inequality comparisons on strings (like you're doing) and on actual numbers.
When used on strings, it's comparing alphabetically, not numerically
You should convert all inputs to numbers, not compare them as strings (the default return type of input function). Similarly, don't cast your random digits to strings
I'm currently trying to make a program in Python that basically asks you math problems. For some reason, there's a lot of errors, and I have no idea why, such as the "!==" function, which seems to be incorrect. There might also be some other issues as I've only just started Python. Could someone direct me to how to use the !== function correctly and also my other issue: Making my input for "addition, subtraction, or multiplication" into a possible command?
# import random
import time
choice = 0
counterright = 0
counterwrong = 0
def add_question_to_file(a, b):
with open("wrong_answers.txt", 'a') as f:
f.write(f"{a} {operation} {b}\n")
def test(a,operation,b):
user_input = int(input(f"{a} {operation} {b} = "))
if user_input == a + b:
print("You got it right!")
counterright += 1
while user_input != a + b:
if user_input == a + b:
print("You got it right!")
counterwrong += 1
break
else:
add_question_to_file(a, b)
print("Try Again!")
user_input = int(input(f"{a} + {b} = "))
def get_question():
a = random.randint(1, 10)
b = random.randint(1, 10)
with open("calc_log.txt", 'a') as f:
if a<b: #insures a is always greater than b
a, b = b, a
f.write(f"{a} {operation} {b}\n")
def check_operation():
if operation !==t "+" or "-" or "*"
print("Sorry, that's invalid. You have to choose of the three operations!")
t1=time.perf_counter() #
m = input("What mode would you like to use? Review/Normal. Choose Normal if this is your first time!")
operat ion = input("Which operation would you like to use? +,-,or *?")
if m == "review":
with open("wrong_answers.txt", 'r') as f:
for line in f:
a, operation, b = line.split()
test(int(a), int(b))
elif m == "normal":
num_questions = int(input("How many questions would you like to do? "))
for i in range(num_questions):
print(f"You are on question {i + 1}: ")
get_question()
t2=time.perf_counter() #
print("It took you", t2-t1, "seconds for you to solve this problemset") #
print ("You got",counterright,"correct and",counterwrong,"wrong.")
The reason !== isn't working is because this is not an operator in python. Try using !=. It means not equal too.
The does not equal function in python is !=. The double equal sign (==) is only used when you want to check for equality. I hope this helps!
I am new to Python, so I decided to start with a numbers game. I have my numbers being input correctly, but I would like it to display the number of correct answers and the correct original, random numbers.
Code as follows:
import random
print('============================')
print('Now try to guess a list of numbers! The range of number is 0-10')
print('How many numbers do you want?')
numberOfNumbers = int(input('Enter the number: '))
counter = 0
answers = [random.randint(0, 10), numberOfNumbers]
values = []
numCorrect = 0
print('Enter your ' + str(numberOfNumbers) + ' numbers.')
while numberOfNumbers != counter:
counter += 1
values.append(int(input("Enter number " + str(counter) + ": ")))
if values == answers:
numCorrect += 1
print('You got' + numCorrect + ' correct!')
print('Original: ' + str(answers))
print('Your guess: ' + str(values))
Current output:
Now try to guess a list of numbers! The range of number is 0-10
How many numbers do you want?
Enter the number: 3
Enter your 3 numbers.
Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
Original: [5, 3]
Your guess: [1, 2, 3]
Target Output:
Now try to guess a list of numbers! The range of number is 0-10
How many numbers do you want?
Enter the number: 3
Enter your 3 numbers.
Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
(Currently not working for print) You got (x) Correct!
(Here prints answers, it's only printing two numbers) Original: [5, 3, x]
(Your input prints here, working as planned) Your guess: [1, 2, 3]
You do this:
values.append(int(input("Enter number " + str(counter) + ": ")))
if values == answers:
numCorrect += 1
But, since you keep appending to values, it will never be equal to (==) answers until all the correct answers are in there, and even then only if they are in the correct order.
If you want numCorrect to have the number of answers in values that is currently correct, you can write something like:
numCorrect = len([v for v in values if v in answers])
Of course, if you only want to print numCorrect if it changes, you have a bit more code to write.
(also note that this goes sideways if you have duplicate correct answers, so it's not quite this simple, but I'm not writing your game, just correcting your code so it does what you appear to want it to do)
You do this:
answers = [random.randint(0, 10), numberOfNumbers]
That creates a list with two numbers, a random number and numberOfNumbers. It looks like you really want a list of length numberOfNumbers with all random numbers:
answers = [random.randint(0, 10) for _ in range(numberOfNumbers)]
This could include duplicates, but you get to figure out how to avoid that.
In general, I would recommend using a free IDE like PyCharm or Spyder to debug your code. They have options that allow you to step through your code one line at a time, so you can see how the values of variables change as your commands execute - that will make a lot more sense.
Since you are pretty new to python I decided to stick to your code and correct them instead of complicating it. So, what you basically did wrong was that you were using print('You got ' + str(numCorrect) + ' correct!') inside the if statement because if the condition wasn't true the print statement wouldn't work.
The next was that you needed to get the random numbers inside while loop to get the x number of random numbers. Or, else what you were doing was that you simply got one random number and the input from numberOfNumbers.
Here's the final code:
import random
print('============================')
print('Now try to guess a list of numbers! The range of number is 0-10')
print('How many numbers do you want?')
numberOfNumbers = int(input('Enter the number: '))
counter = 0
answers = []
values = []
numCorrect = 0
print('Enter your ' + str(numberOfNumbers) + ' numbers.')
while numberOfNumbers != counter:
ans_var = random.randint(0,10)
answers.append(ans_var)
counter += 1
values.append(int(input("Enter number " + str(counter) + ": ")))
if values == answers:
numCorrect += 1
print('You got ' + str(numCorrect) + ' correct!')
print('Original: ' + str(answers))
print('Your guess: ' + str(values))
Hope it helps :)
I am writing a program which will test arithmetic skills.
It is supposed to generate random questions, and give a random operation.
Here is my code:
import random
score = 0
counter = 0
ops = ['+', '-', '*', '/']
def question():
num1 = random.randint(0,10)
num2 = random.randint(1,10) #Starts from 1 to avoid zerodivision error
operation = random.choice(ops)
question = float(input(f"What is {num1} {operation} {num2}?: "))
global answer
answer = eval(str(num1) + operation + str(num2))
global counter
counter = counter + 1
def points():
while counter < 10:
question()
if question == answer:
print("\nCorrect!\n")
global score
score = score + 1
else:
print(f"\nWrong! The answer is {answer}\n")
points()
print(f"\nYou got {score} out of {counter}")
But it gives this output:
What is 9 + 3?: 12
Wrong! The answer is 12
It is supposed to say correct if the input matches the answer, and count a score, and print the score out of ten at the end.
Please help me fix this.
The problem is in
if question == answer:
In that line, question is a reference to the function question() that you defined earlier. Since answer is some int holding the answer to the question, the == is always False. You never actually find out what the user typed in.
To fix that, do something like this:
def question():
num1 = random.randint(0,10)
num2 = random.randint(1,10) #Starts from 1 to avoid zerodivision error
operation = random.choice(ops)
user_answer = float(input(f"What is {num1} {operation} {num2}?: "))
global answer
answer = eval(str(num1) + operation + str(num2))
global counter
counter = counter + 1
return user_answer
def points():
while counter < 10:
user_answer = question()
if user_answer == answer:
print("\nCorrect!\n")
global score
score = score + 1
else:
print(f"\nWrong! The answer is {answer}\n")
I've changed the name to make it more clear what's going on.
As an addendum, I would highly, highly recommend not using global variables. They are almost never necessary and generally confuse the issue. For example, I think that
def question():
num1 = random.randint(0,10)
num2 = random.randint(1,10) #Starts from 1 to avoid zerodivision error
operation = random.choice(ops)
user_answer = float(input(f"What is {num1} {operation} {num2}?: "))
real_answer = eval(str(num1) + operation + str(num2))
return user_answer, real_answer
def points():
score = 0
for questions_asked in range(1, 11):
user_answer, real_answer = question()
if user_answer == real_answer:
print("\nCorrect!\n")
score += 1
else:
print(f"\nWrong! The answer is {answer}\n")
This makes it much easier to understand the program flow.
Your question has already been answered by Josh Karpel, but I just thought I'd point out another issue with division.
Division will always result in a float instead of an int, so if the user says 4 / 2 is 2... the script will say the answer is wrong, because it's doing a stringy comparison of "2" with "2.0". That's why in Josh's version, he converts the user answer to a float. This way the answers are compared numerically.
Additionally, the script is currently capable of asking things like What is 4 / 7 ? which is difficult for a person to answer. One work around would be to randomise num2 until it is evenly divisible by num1.
def question():
num1 = random.randint(0, 10)
num2 = random.randint(1, 10)
operation = random.choice(ops)
if operation == '/':
while num1 % num2 != 0:
num2 = random.randint(1, 10)
# do eval
I am supposed to write a program in python that asks the user how many multiplication questions they want, and it randomly gives them questions with values from 1 to 10. Then it spits out the percentage they got correct. My code keeps repeating the same set of numbers and it also doesn't stop at the number the user asked for. Could you tell me what's wrong?
import random
import math
gamenumber = int(input("How many probems do you want?\n"))
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
def main():
random.seed()
count = 0
while count < gamenumber:
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
answer = str(num_1*num_2)
correct = guess == answer
if guess == answer:
print("Correct!")
else wrong:
print("Sorry, the answer is", answer, ".")
result = correct/wrong
print("You got ", "%.1f"%result, "of the problems.")
main()
You only assign to num_1 and num_2 once. Their values never change; how can your numbers change? Furthermore, you don't increment count, so its original value is always compared against gamenumber.
You need to assign a new random number to your two variables and increment your counter.
You forgot to increment count in your loop and num_1 and num_2 don't get new values.
Problems you mentioned
My code keeps repeating the same set of numbers
This is no surprise, as you set your num_1 and num_2 (1) outside the main function and (2) outside the main while loop. A simple correction is:
while count < gamenumber:
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
My code doens't stop at the number asked for:
There again, no surprise, as you never increment the count counter: you always have count < gamenumber.
A simple correction is:
while count < gamenumber:
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
answer = str(num_1*num_2)
count += 1
Here, the count += 1 means add 1 to count *in place*. You could also do count = count + 1 but it's a bit less efficient as you create a temporary variable (count + 1) that you don't really need.
Other problems
You never define wrong
You define gamenumber outside the function. While it's not an issue in this case, it'd be easier to use gamenumber as an argument of main, as it's the variable that drives the game.
Your result is defined in the loop. You probably want to increment a counter for each good answer and print the result after the main loop.
Your result is calculated as correct/wrong. While I'm sure you meant correct/gamenumber, you have to be extra careful: count and gamenumber are integers, and dividing integers is no the same as dividing floats. For example, 2/3 gives 0, but 2/float(3) gives 0.6666666. So, we'll have to use a float somewhere.
You want to print a percentage: your result should then be result=correct*100./gamenumber.
You don't want to gamenumber to be 0, otherwise your result will be undefined.
So, all in all, your main function should be
def main(gamenumber):
random.seed()
count = 0
correct = 0
while count < gamenumber:
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
answer = str(num_1*num_2)
count += 1
if guess == answer:
correct += 1
print("Correct!")
else wrong:
print("Sorry, the answer is", answer, ".")
if gamenumber > 1:
result = correct * 100./gamenumber
print("You got ", "%.1f"%result, "of the problems.")
The most glaring issue to me is that you have an infinite loop; you don't increase count anywhere.
You're only generating the question numbers once, before you start looping. You need to generate num_1 and num_2 every time, before the user is asked a question.
You never actually update the count value after initializing it, so your loop will go on forever.
import random
import math
spelling of "problems" is wrong
gamenumber = int(input("How many probems do you want?\n"))
move these next two lines inside the loop
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
def main():
random.seed()
count = 0
while count < gamenumber:
You can use "What is {}x{}?".format(num1, num2) here.
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
answer = str(num_1*num_2)
Is this supposed to count the correct answers? should be correct += guess == answer
correct = guess == answer
Do you mean to count the number of wrong answers? wrong += guess != answer
if guess == answer:
print("Correct!")
else wrong: is a syntax error else: #wrong perhaps?
else wrong:
print("Sorry, the answer is", answer, ".")
This isn't how to compute a percentage. You should use correct*100/gamenumber and dedent to match the print()
result = correct/wrong
print("You got ", "%.1f"%result, "of the problems.")
main()
Also you're not incrementing count anywhere. It's easier to just use
for count in range(gamenumber):
instead of the while loop
Python is a procedural language. It executes statements in your method body from top to bottom. This line:
num_1 = random.randint(1,10)
is an assignment statement. It does not equate num_1 with a random process for assessing its value; it evaluates an expression - by calling random.randint(1,10) - and assigns that value to num_1, once.
You must force another call to random.randint to obtain another random number, and you must have a statement assign a value to num_1 each time you want num_1's value to change.
Write a multiplication game program for kids. The program should give the player ten randomly generated multiplication questions to do. After each, the program should tell them whether they got it right or wrong and what the correct answer is
from random import randint
for i in range (1,11):
num1 = randint (1,10)
num2 = randint (1,10)
print ("Question",i,":",num1,"*",num2,"=", end = " ")
guess = int (input())
answer = num1*num2
if guess == answer:
print ("Right!")
else:
print ("Wrong. The answer is: ",answer)