How to print variables depending on an operator in python? - 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)

Related

Python SyntaxError: cannot assign to operator

The following Python script raises syntax error:
def main(number, number2, equation):
if equation == 1:
number + number2 = answer
SyntaxError: cannot assign to operator is the raised error. Please help.
You must assign (=) operation (number + number2) to variable answer in this direction.
answer = number + number2
Variable name is on right side and value, expression, object, etc. is on the left.
In python you set variables to be equal to the their result instead of the result to be equal to the variable.
So where you have put
number + number2 = answer
You need to do
answer = number + number2
As what you are doing is making the sum of number and number2 equal to answer which is not possible

your program produce no output [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am new to the field. simple program, all I need to do is to find the smallest number.
number1 = input ('')
number2= input('')
number3 = input('')
number1 = input ('')
number2= input('')
number3 = input('')
if (number1<number2) and (number1<number3):
smallest=number1
elif (number2<number1) and (number2 < number3):
smallest=number2
else:
smallest=number3
print(smallest)
This occurs because input() returns a string:
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
Because of this, all checks amongst the input values won't be between integers, as you want, but strings, leading to comparisons being based upon lexicographical ordering rather than value. This can be solved by converting the inputs to integers:
number1 = int(input(''))
number2 = int(input(''))
number3 = int(input(''))
if (number1 < number2) and (number1 < number3):
smallest = number1
elif (number2 < number1) and (number2 < number3):
smallest = number2
else:
smallest = number3
print(smallest)
simply use min() and max()
n1,n2,n3 = 1,2,3
print("min:", min(n1,n2,n3) )
print("max:", max(n1,n2,n3))
output:
> min: 1
> max: 3
When you enter "7", "15", and "3", your program compares those three values as strings, which means that it will find the one that is "smallest" alphabetically -- the first character is compared first, which makes "15" come first in the ordering (then "3", then "7").
To fix this, you need to convert the values to ints:
number1 = int(input())
You may be getting blank strings ("") in some cases because you copied and pasted the input lines, which means you're getting prompted six times and only the last three times count.
Overall the fixed version of your code would look like:
number1 = int(input())
number2 = int(input())
number3 = int(input())
if number1 < number2 and number1 < number3:
smallest = number1
elif number2 < number3:
smallest = number2
else:
smallest = number3
print(smallest)
Note that you don't need to pass an empty string to input() (it defaults to an empty string), and you don't need the parentheses around your comparison operations (because < already takes precedence over and).
A shortened version of this code that uses min and a loop would be:
print(min(int(input()) for _ in range(3)))
In this line of code, the expression int(input()) for _ in range(3) generates three inputs (one per number in range(3)), and the min function finds the minimum value from that generator. The nice thing about using a loop like this is that you can easily make it work for any number of inputs without having to write a bunch more if ... < ... checks!
When you use input(''), it takes the number from terminal (at the running time), so your code is OK, just to understand how it works, run your modified code below, some added strings can help you find your problem better.
number1 = input('Please insert the first number ?')
number2 = input('Please insert the second number ?')
number3 = input('Please insert the third number ?')
if (number1 < number2) and (number1 < number3):
smallest = number1
elif (number2 < number1) and (number2 < number3):
smallest = number2
else:
smallest = number3
print("result is : ", smallest)

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}

Python Invalid Syntax on simple Maths Program

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

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)

Categories

Resources