Python Invalid Syntax on simple Maths Program - python

I am trying to create a random maths question quiz but the colon comes up as invalid syntax. Is it due to the operator I can not use the colon? If I take it out it is also seen as invalid syntax.
This is the code to create the 'correct_answer' variable so if the users in putted answer is correct or incorrect it lets them know. If the whole code is needed (which I'm sure it won't be as this is probably something really stupid i'm missing) I can post it.
if operator==+:
correct_answer=random_number1+number2
elif operator==-:
correct_answer=random_number1-number2
else:
correct_answer=random_number1*number2
FULL CODE:
import random
name=raw_input("Hi what's your name?")
print "Alrighty lets go, "+name+"!"
for i in range(10):
operator_list=('+','-','x')
operator=random.choice(operator_list)
random_number1=random.randint(1,12)
random_number2=random.randint(1,10)
question=1
print random_number1, operator, random_number2
if operator==+:
correct_answer=random_number1+number2
elif operator==-:
correct_answer=random_number1-number2
else:
correct_answer=random_number1*number2
answer = eval(str(int(raw_input("What is the answer?"))))
if answer==correct_answer:
print "Great job!"
else:
print"Unlucky pal! It was " +correct_answer+ "
question+1

I'm assuming that + and - are strings. If so, you need quotes around them. It's also good practice to space out your code to make it more legible.
if operator == '+':
correct_answer = random_number1 + number2
elif operator == '-':
correct_answer = random_number1 - number2
else:
correct_answer = random_number1 * number2

ANSWER: All that was needed were speech marks around the operator.
if operator == "+":
correct_answer=random_number1+number2
elif operator == "-":
correct_answer=random_number1-number2
else:
correct_answer=random_number1*number2

Ans:
When you wrote + and - , python took it as a real for integer operator and gave it an error because there were no numbers. Adding " " will define it as a string and should not give a error.
Corrected version:
if operator == "+":
correct_answer=random_number1+number2
elif operator == "-":
correct_answer=random_number1-number2
else:
correct_answer=random_number1*number2

Related

Why do the math problems in my program repeat the same equation? [closed]

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 6 months ago.
This post was edited and submitted for review 6 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
So, I'm trying to make a math problem in Python, since I'm a beginner learning how to code. Basically, it asks you how many questions you want to answer, and to answer questions of addition, subtraction, multiplication, and division correctly.
Let me show you the code I have, so far.
import random
num_question = (int)(input("Enter how many questions would you like to solve: "))
num1 = random.randint (0,20)
num2 = random.randint (0,20)
oper = ["+","-","*","/"]
operator = random.choice(oper) #chooses a variable in the "oper" list at random. Then it is used in the question
for count in range (0, num_question):
question = (num1, operator, num2) #e.g. What is 6 - 2
print (question)
guess = (int)(input("Enter here: "))
answer = 0
if operator == "+": #if the operator chooses addition, the answer will equal the sum of both numbers. The same goes for the other if statements.
answer = (num1 + num2)
elif operator == "-":
answer = (num1 - num2)
elif operator == "*":
answer = (num1 * num2)
elif operator == "/":
answer = (num1 / num2)
if guess == answer: #if the answer is equal to the question, then it's correct and proceeds. Otherwise, it doesn't.
print ("Correct!")
continue
else:
print ("Incorrect. Please try again.")
However, the drawback is that the same question repeats everytime (I am using my old laptop, so the p button and the quotation button is broken). Now my question is how to make the questions not repeat themselves.
There are a couple problems.
You are testing for equality with "==" inside the "if" statements, when you probably would like to assign the true answer to a variable to compare to the user's guess
You are comparing the answer to the question, which is a string, which will never be equal
Fix the first one by creating a new variable for the true answer to keep it separate from the guess. Fix the second by comparing the guess to the real answer.
guess = (int)(input("Enter here: "))
answer = 0
if operator == "+": #if the operator chooses addition, the answer will equal the sum of both numbers. The same goes for the other if statements.
answer = (num1 + num2)
elif operator == "-":
answer = (num1 - num2)
elif operator == "*":
answer = (num1 * num2)
elif operator == "/":
answer = (num1 / num2)
if answer == guess : #if the answer is equal to the question, then it's correct and proceeds. Otherwise, it doesn't.
print ("Correct!")
break
answer == (num1 + num2)
You're using two equal signs, which is an equality test, not an assignment.
You're overwriting the user's answer with the correct result. Then you're comparing that with the question text, not the user's answer.
Also you need to use = to assign, not ==.
Use a different variable for the correct answer, and compare that with the user's answer.
or count in range (0, num_question):
question = ("What is " + str(num1) + " " + operator + " " + str(num2) + "?") #e.g. What is 6 - 2
print (question)
answer = int(input("Enter here: "))
if operator == "+": #if the operator chooses addition, the answer will equal the sum of both numbers. The same goes for the other if statements.
correct = (num1 + num2)
elif operator == "-":
correct = (num1 - num2)
elif operator == "*":
correct = (num1 * num2)
elif operator == "/":
correct = (num1 / num2)
if correct == answer:
print ("Correct!")
break
else:
print ("Incorrect. Please try again.")

How to print variables depending on an operator in python?

I am trying to code a simple calculator but I am having a problem. I can't seem to add, subtract, multiply, or divide two variables and print them. I am trying to code so the user can input the numbers along with the operator. Any ideas?
Thanks,
SanguineL
number1 = raw_input ("What is the first number?")
operator = raw_input ("What is the operator?")
number2 = raw_input ("What is the second number?")
elif operator == +
answer = number1 + number2
elif operator == -
answer = number1 - number2
elif operator == *
answer = number1 * number2
elif operator == /
answer = number1 / number2
print answer
You need to distinguish the string you get from raw_input from the function an operator represents.
if operator == "+":
answer = number1 + number2
elif ...
The operator module lets you build a dictionary that abstracts away the lookup process:
import operator
number1 = raw_input ("What is the first number?")
op = raw_input ("What is the operator?")
number2 = raw_input ("What is the second number?")
funcs = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div}
try:
f = funcs[op]
except KeyError:
raise ValueError("Undefined operator %s" % (op,))
answer = f(number1, number2)
So there's a couple issues with your code, the first issue is that raw_input will always assume the input is a string and so your number1, operator, and number2 objects will be strings (and I assume you only want the operator variable to be a string). If you want to convert your numbers to floats, then you need to write something like number1 = float(raw_input ("What is the first number?"))
The second issue is that you need to start an if block with an if statement not an elif statement. elif statements come only after the if statement since it stands for "else if" - i.e. in the form if something else if something.
The third issue is that you didn't put quotes around your operators in your conditional statements. Python will not automatically assume they are strings. Python will assume they are variables which you haven't declared yet. You should have a statement like elif operator == '-' in order to make the comparison valid.
The fourth and last issue (that I see) is that since you are using raw_input it appears you are using python 2. Python 2 has a weird behavior when using the division operator / - namely it floors the division if the inputs to it are ints or longs. That behavior can cause a lot of headaches if you are not aware of it. You should probably include a from __future__ import division line at the beginning of your code so dividing doesn't floor the answer.
Don't know what does raw_input ("What is the first number?") mean (assume that is some kind of form input or sdt_in), but lower part might be (don't forget to convert your inputs like this number1 = int(number1)):
if operator == '+'
answer = number1 + number2
elif operator == '-'
answer = number1 - number2
elif operator == '*'
answer = number1 * number2
elif operator == '/'
answer = number1 / number2
print(answer)

Make python ask questions from strings

I want to make python ask questions to the user - from random variables in lists.
It needs to ask the question requiring an input from the user.
This is my code so far:
import time
import random
question = "0"
score = "0"
name = input("What is your full name?")
print ("Hello " + name, "welcome to The Arithmetic Quiz")
time.sleep(2)
numbers = list(range(1, 50))
operators = ["+", "-", "*"]
numbers1 = list(range(1,10))
print(str(random.choice(numbers)) + random.choice(operators) + str(random.choice(numbers1)))`
How would I make the last line of code ask a question and get an input from the user?
Also how would I make it so that python says whether this is correct when I do not know what python will ask?
The answer is already in your code.
user_input = input(str(random.choice(numbers)) + random.choice(operators) + str(random.choice(numbers)) + "? ") should work.
It gets a sample random number from numbers, gets a random operator from operators, gets another random number from numbers, and stores the input to the variable user_input.
To get Python to check your answer, store the randomly generated arguments inside variables and check them. (If there is a better way of doing this, I would appreciate it if someone pointed it out to me).
operand1 = random.choice(numbers)
operand2 = random.choice(numbers)
operator = random.choice(operators)
if operator == '+':
answer = operand1 + operand2
elif operator == '-':
answer = operand1 - operand2
else:
answer = operand1 * operand2
user_input = input(str(operand1) + operator + str(operand2) + "? ")
if str(answer) == user_input:
print('Correct!')
else:
print('Wrong!')
EDIT: #mhawke's answer has a better way of storing and manipulating the operands. Instead of storing the operators in a list, store them in a dict and map them to their corresponding operator function as so:
import operator
operators = {"+": operator.add, "-": operator.sub, "*": operator.mul}
operand1 = random.choice(numbers)
operand2 = random.choice(numbers)
op = random.choice(operators)
expected_answer = op(operand1, operand2)
Documentation for operator.
For the second part of your question, how to determine whether the user entered the correct answer, you can store the randomly selected values and evaluate the resulting expression. Then compare that to the user's value:
import operator
operators = {"+": operator.add, "-": operator.sub, "*": operator.mul}
operand1 = random.choice(numbers)
operand2 = random.choice(numbers1)
op = random.choice(operators)
expected_answer = op(operand1, operand2)
user_answer = input('{} {} {} = ?: '.format(operand1, op, operand2)
if int(user_answer) == expected_answer:
print('Correct!')
else:
print('Wrong. The correct answer is {}'.format(expected_answer)
The operators are stored in a dictionary. The operator tokens (+, -, *) are the keys in this dictionary, and the values are functions from the operator module that perform the operations. Using a dictionary like this is very flexible because if you wanted to support a new operator, e.g. division, you can just add it to the operators dictionary:
operators = {"+": operator.add, "-": operator.sub, "*": operator.mul, '/': operators.div}

Random Maths Program

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)

Confusing result from raw_input() in Python

I'm having problems with the "operator" variable. So far I have only tried +. It doesn't seem to register and I can't figure out why. i'm using the online python interpreter on repl.it because I'm having problems with my computer.
EDIT: I should probably add that I just started learning Python (I had some Java experience but it was years ago). I'm trying to create a simple text calculator.
restart=raw_input("to restart calculations enter \'true\'")
#if restart == "true":
#stuff
numone=raw_input("Enter the first number: ")
operator = raw_input("Enter the operator(+,-,*,/):")
operator = str(operator)
numtwo=raw_input("Enter another number: ")
print("operator: " + operator)
if operator== '+':
answer=numone+numtwo
print(answer)
print("test")
if operator == "-":
answer=numone-numtwo
print(answer)
else:
print("something went wrong")
#if operator == "*":
Your problem is that you're concatenating two strings, you should cast to int before:
answer = int(numone) + int(numtwo)
Why? Because raw_input reads the input as string.
Give elif to the second statement
since user give '+'
first if statment excutes but in next statement it fails and go to the else so for + you get two result both addition and something wrong
and also you need to convert the operands to integer
one more thing while converting to integer you need check right conditions for integer else it will give error
numone=raw_input("Enter the first number: ")
operator = raw_input("Enter the operator(+,-,*,/):")
operator = str(operator)
numtwo=raw_input("Enter another number: ")
print("operator: " + operator)
if operator== '+':
try:
answer=int(numone)+int(numtwo)
print(answer)
print("test")
except ValueError:
print "one of the operand is not integer"
elif operator == "-":
try:
answer=int(numone)-int(numtwo)
print(answer)
print("test")
except ValueError:
print "one of the operand is not integer"
else:
print("something went wrong")

Categories

Resources