I am trying make a maths game but the output says wrong when I answer it correctly. (on python 2.7.2)
The code:
import random
number1 = random.randrange(1, 10)
number2 = random.randrange(1, 10)
print "Whats",number1,"+",number2
answer = raw_input('=')
if answer is (number1 + number2):
print "Correct!"
else:
print "Wrong!"
You want to use == instead of is. is is used for checking reference equality. You can look at this for a better explanation. raw_input reads values in as strings by default, so you need to convert it to an integer to be able to check if the input is equal to the answer. Or more simply, use input instead.
import random
number1 = random.randrange(1, 10)
number2 = random.randrange(1, 10)
print "Whats",number1,"+",number2
answer = input('=')
if answer == (number1 + number2):
print "Correct!"
else:
print "Wrong!"
Related
i have an awfully simple and obtuse question, i hope this is the right place to ask this:
i wrote a program that generates two random integers, adds them together and prompts the user for an answer. if the user gets it wrong the question is prompted again until they get it right-- this is where the while loop comes into play and so i implemented it like this:
import random
number1 = random.randint(0, 99)
number2 = random.randint(0, 99)
answer = eval(input("What is {numberA} + {numberB}? ".format(numberA=number1, numberB=number2)))
check = answer == number1 + number2
if answer == number1 + number2:
print("{numberA} + {numberB} = {Answer}".format(numberA=number1, numberB=number2, Answer=answer))
while answer != number1 + number2:
eval(input("That's not right. Try again: "))
print("yes that is right")
what ended up happening instead was that while loop ended up going on forever, when i instead changed the while statement to this:
while answer != number1 + number2:
answer = eval(input("That's not right. Try again: "))
it worked and the print statement that followed it was executed it immediately. what i don't understand was why did my mistake make the loop go on for infinity? how does redefining the answer variable in that statement make the while loop condition false?
In your erroneous version, answer never changes, so once your code enters the loop (because answer != number1 + number2) the condition remains true forever.
You never modified answer in your original code. If the condition existed where the loop would start, nothing ever changed the state so that the test would fail and the loop would end.
import random
number1 = random.randint(0, 99)
number2 = random.randint(0, 99)
correct_answer = number1 + number2
answer = int(input("What is {numberA} + {numberB}? ".format(numberA=number1, numberB=number2)))
while answer != number1 + number2:
answer = int(input("That's not right. Try again: ".format(numberA=number1, numberB=number2)))
if answer == correct_answer:
break
print("yes that is right")
answer never changes, you can fix this by simply adding
if answer == correct_answer:
break
in the
while answer != number1 + number2:
loop.
In my code I'm making a basic multiplying game.
But in my game,
When you get the answer right, it says you got it wrong
Here's my whole code:
import random
score = 0
while True:
num1 = random.choice(range(1,12))
num2 = random.choice(range(1,12))
answer = num1 * num2
a = input("Solve for " + str(num1) + "x" + str(num2))
if a == answer:
print("congrats you got it right")
score += 1
else:
print("Wrong sorry play again")
print("Score was: " + str(score))
break
When I get the right answer I get
Solve for 7x10 70
Wrong sorry play again
Score was: 0
Other languages might let you get away with this, but Python is strongly typed. The input function gets a string, not a number. Numbers can't be equal to strings. Either convert the number to a string or the string to a number before you compare them. You can use str or int to convert.
Function input returns what was typed as a string... in order to compare it with the answer, you need to either convert it to int:
if int(a) == answer:
or the other way around (convert answer to str):
if a == str(answer):
The first one may raise an exception if a is not parseable to an int.
Here the docs.
PS: I really wonder how ur random library picked a 1070 sampling from 0 to 11...
Or use int(input()):
import random
score = 0
while True:
num1 = random.choice(range(1,12))
num2 = random.choice(range(1,12))
answer = num1 * num2
a = int(input("Solve for " + str(num1) + "x" + str(num2)))
if a == answer:
print("congrats you got it right")
score += 1
else:
print("Wrong sorry play again")
print("Score was: " + str(score))
break
I have an assignment that requires me to print 10 random sums, then get the user to enter their answers. I know how to randomly generate numbers, but I need to print the whole sum out, without giving the answer, but with the string I am using it adds them automatically.
This is my code below:
for i in range(10):
number1 = (random.randint(0,20))
number2 = (random.randint(0,20))
print (number1 + number2)
answer = input("Enter your answer: ")
If someone could help me out I would appreciate it, I believe the line
print (number1 + number2)
is the problem, as it is adding them when I just want the random numbers printed in the sum.
Thanks in advance,
Flynn.
Try this,
print number1, '+', number2
Your following line first computes the sum of the two numbers, then prints it
print (number1 + number2)
you have to print a string:
print(str(number1) + " + " + str(number2))
or prefer formating features instead of concatenation:
print("{} + {}".format(number1, number2))
or:
print("%s + %s" % (number1, number2))
Finally, you may want to read some doc:
str.format
string formatting with the % operator
Python tutorial
To convert numbers to a string for concatenation use str().
print str(number1) + ", " + str(number2)
or using natural delimiter
print number1, number2
(The , tells python to output them one after the other with space. str() isn't really necessary in that case.)
This should do the job:
from random import randint
for i in range(10):
num1 = randint(0,20)
num2 = randint(0,20)
answer = input('Sum of %i + %i?: ' % (num1,num2)
Perhaps you know what to do with the rest? (e.g. handling the answer section)
When I type the input of the sum of number1 + number2 as "answer" and number1, number2 are two randomized numbers between 1-500, I get my "Wrong, sorry!" statement instead of the "Right!" when the answer is correct.
For example, if the two numbers are 479 + 121, the answer should be 600, right? Well, apparently it's not, my code likes to say. Due to some error logic, I'll guess. (Note this is just an excerpt, obviously. The variables were declared as integers before in the main module and random is imported.)
def getNumbers():
number1 = random.randint(1, 500)
number2 = random.randint(1, 500)
return number1, number2
def getAnswer(number1, number2, answer):
print("What is the answer to the following equation:")
print(number1)
print("+")
print(number2)
answer = input("What is the sum? ")
return answer
def checkAnswer(number1, number2, answer, right):
if answer == number1 + number2:
print("Right!")
else:
print("Wrong, sorry!")
It comes out as:
What is the answer to the following equation?
479
+
121
What is the sum? 600
Wrong, sorry!
0 also comes in as incorrect, so I'm not sure what the value is being set to. Any idea how to fix this code?
input function returns string , you should cast it to int :
answer = int(input("What is the sum? "))
because you didn't cast it to int "600" == 600 is always False and Wrong printed .
thanks for taking time to read this.
I have to create a program that generates 10 random maths questions based around =, - and *. I have the program working but everytime I run it after the main program it prints "none" even though that's not in my program.Any help at all would be much appreciated. Thank you.
import random
print ("Welcome")
name=input("What's your name?")
print("Nice to meet you", name, ",you will be given 10 multiplication, addition and subtraction questions.")
Num1 = random.randint(1,12)
Num2 = random.randint(1,12)
sign = random.randint(1,3)
if sign == 1: # If the random number generated is 1
question = Num1 + Num2
rightanswer1 = Num1 + Num2
answer1=input(print("What is", question ,"?"))
if answer1 == rightanswer1:
print("Well Done!")
if answer1 != rightanswer1:
print("Sorry, that's incorrect, the answer was", rightanswer1)
if sign == 2:
question = Num1 - Num2
rightanswer2 = Num1 - Num2
answer2=input(print("What is", Num1, "-", Num2 ,"?"))
if answer2 == rightanswer2:
print("Well done!")
elif answer2 != rightanswer2:
print("Sorry, that's incorrect, the answer was", rightanswer2)
if sign == 3:
question = Num1 * Num2
rightanswer3 = Num1 * Num2
answer3=input(print("What is", Num1, "x", Num2 ,"?"))
if answer3 == rightanswer3:
print("Well done!")
elif answer3 != rightanswer3:
print("Sorry, that's incorrect, the answer was", rightanswer3)`
> Welcome
> What's your name? John
> Nice to meet you John ,you will be given 10 multiplication, addition and subtraction questions.
> What is 12 x 3 ?
> None 36
> Sorry, that's incorrect, the answer was 36
I think you are using python 3. In python 3 input is like raw_input in python 2. So you get the string as input. So convert it into int
var = int(input("Enter a number: "))
So in your code make it as
print("What is", Num1, "x", Num2 ,"?")
answer3 = input()
answer3 = int(answer3)
See this:
whats-the-difference-between-raw-input-and-input-in-python3-x
I'm reluctant to just give you an answer that just does it for you, so instead i'll provide you with a few hints to improve things. (i.e. this isn't an answer, just too large of a comment - and more like a codereview answer)
First off, you use a structure like this:
if x == 1:
#do something
if x == 2:
#do something else
...
In this case, which it makes no difference, it is easier to read if you use the if syntax as intended:
if <condition>:
#do this if the above test is true.
elif <more conditions>:
#do this only if the first test is false and this one is true
elif <more conditions>:
#same as above, except for the second test must be false too
else:
#do this if all the above tests are false
So you could use this something like:
if sign == 1:
...
elif sign == 2:
...
elif sign == 3:
...
else:
# something weird happened...
Which would make that section of the program easier to follow.
The same thing can be done with the if answer1 == rightanswer1: sections;
if answer1 == rightanswer1:
#correct!
else:
#incorrect.
That would be a clearer was to do it. You seem to have used the if...elif style in a couple of them, but not the first one.
Once you have this, it will be a little clearer.
The next way you could improve things is by removing duplicated code. You don't need separate branches for each sign, you can just roll it all into one:
number1 = randint(1,12)
number2 = randint(1,12)
op = randint(1,3)
question_string = "%d %s %d = ?" % (number1, number2, ["+", "-", "*"][op])
result = None
if op == 1:
result = number1 + number2
elif op == 2:
result = number1 - number2
elif op == 3:
result = number1 * number2
This will do most of the logic for you, and generate the strings you want, without duplicating all of the other code.
Small changes like this can make things much more readable.
It's printing None because the print() function returns None and you're passing that value of None from print() as the prompt to your input() functions. Eg,
answer3=input(print("What is", Num1, "x", Num2 ,"?"))
So print("What is", Num1, "x", Num2 ,"?") prints its stuff, and returns None, which then gets printed as the prompt by input().
A simple way to fix this is to just move your print() function calls out of your input() functions.
Eg,
print("What is", Num1, "x", Num2 ,"?")
answer3=input()
However, there's another major problem with your program: the rightanswer variables are ints, but the inputted answers are strings. To compare them properly they need to be the same type. So you should either convert the inputted answers to int, or alternatively, convert the rightanswers to str.
There are two problems with how you use the input function:
You misuse the prompt argument
You forget to convert the result
First, have a better look at the reference of the input function
The prompt argument
input takes a string as argument that will be displayed ("prompted") to the user to indicate that the program is waiting an input. The print function also displays a string to the user, but it doesn't return anything. It does its job and that's all (and in Python a function that returns nothing, returns None). That's what input gets to display, so it displays None. You should use format instead. It will format and return the formatted string that input can display:
answer1_as_str=input("What is {} ?".format(question))))
or
answer2_as_str=input("What is {:d} - {:d} ?".format(Num1, Num2)))
The return value
input returns the user input as a string contrary to python 2 (i.e. exactly as entered). So you have to convert the input to the desired type if you need it. If you type 10 for example, the input will return "10". If you need an int, you have to convert it yourself.
answer1 = int(answer1_as_str)
It looks like you don't really understand how input() works. You might also want to review the different datatypes and conditional statements. Other than that, it was a very good attempt. Here's my solution:
from random import randint
print("Welcome")
name = input("What's your name?\n")
print("Nice to meet you " + name + ", you will be given 10 multiplication, addition and subtraction questions.")
for i in range(10):
print("\nProblem " + str(i+1))
num1 = randint(1,12)
num2 = randint(1,12)
sign = randint(1,3)
if sign == 1:
question = str(num1) + " + " + str(num2)
answer = num1 + num2
elif sign == 2:
question = str(num1) + " - " + str(num2)
answer = num1 - num2
else:
question = str(num1) + " x " + str(num2)
answer = num1 * num2
user_answer = input("What is " + question + "? ")
if user_answer == str(answer):
print("Well done!")
else:
print("Sorry, that's incorrect, the answer was", answer)