How could I set a variable up for +, - and *?
example of what I'm trying to do for subtraction
difficulty = '-'
FinalAnswer=((Answer1) (Difficulty) (Answer2))
I'm sure this is actually super simple and I'm having a massive brain fart.
The cleanest approach here is to use operator, e.g.:
import operator
operators = {'+': operator.add, '-': operator.sub}
x = operators['-'](a, b)
If you need to evaluate a string like 10 + 3, you could use eval(), e.g.:
s = '10 + 3'
eval(s)
As pointed out in the comment by #Błotosmętek, you cannot use the otherwise far safer option ast.literal_eval() in this case.
You can use eval:
FinalAnswer= eval('Answer1' + Difficulty + 'Answer2')
but this is dangerous if the strings come from user input.
Alternatively, you could do something like that:
FinalAnswer = { '-': Answer1 - Answer2,
'+': Answer1 + Answer2,
'*': Answer1 * Answer2 } [Difficulty]
Depending on how you have your program structured you should just be able to do this with a little bit of control flow.
if difficulty == 1:
operation = '+'
elif difficulty == 2:
operation = '-'
elif difficulty == 3:
operation = '*'
elif difficulty == 4:
operation = '/'
Related
brand new at Python, and been experimenting with various calculator code methods in Python.
I found the following code:
from operator import pow, truediv, mul, add, sub
operators = {
'+': add,
'-': sub,
'*': mul,
'/': truediv
}
def calculate(s):
if s.isdigit():
return float(s)
for c in operators.keys():
left, operator, right = s.partition(c)
if operator in operators:
return operators[operator](calculate(left), calculate(right))
calc = input("Type calculation:\n")
print("Answer: " + str(eval(calc)))
and I'm just wondering how one would formulate an input loop for this one.
from operator import pow, truediv, mul, add, sub
operators = {
'+': add,
'-': sub,
'*': mul,
'/': truediv
}
def calculate(s):
if s.isdigit():
return float(s)
for c in operators.keys():
left, operator, right = s.partition(c)
if operator in operators:
return operators[operator](calculate(left), calculate(right))
cont = 'y'
while cont.lower() == 'y':
calc = input("Type calculation:\n")
print("Answer: " + str(eval(calc)))
cont = input("Do you want to continue? (y/n)")
It would be good to add more validations to the code... like ensuring that only one operator exists and that there are numbers on either side of the operator inside the calc function.
Also, you are importing power but don't have a symbol for it. Can use '^' if you haven't already? It is easier than using '**' which python uses.
The script will ask you continuosly for operation to compute as follows:
while True:
calc = input("Type calculation (C to exit):\n")
if calc.upper().strip() == "C":
break
print("Answer: " + str(eval(calc)))
Note that, as it is, the code is extremely fragile, given that anything which cannot be reconducted to a number operator number pattern (or "C"), will need to be treated. You could use pattern matching to check if the operation is valid before passing to eval first, and manage bad cases as you wish.
Write a python program to display the outputs of following arithmetic operations on two numbers,which is accepted from user side ? a)Addition b)Subtraction c)Multiplication d)Division//
i wrote this code but it is not working
a = int(input("Enter First Number: "))
b = int(input("Enter Second Number: "))
print("Enter which operation would you like to perform?")
ko= input("Enter any of these char for specific operation +,-,*,/: ")
result = 0
if ko == '+':
result = a + b
elif ko == '-':
result = a - b
elif ko == '*':
result = a * b
elif ko == '/':
result = a / b
else:
print("Error")
print(num1, ko , num2, ":", result)
can anybody please tell me what i did wrong or post the correct code
Firstly, the first line of your program isn't indented properly - You need to remove the indentation before the first line.
Here's a guide to proper indentation in python: https://docs.python.org/2.0/ref/indentation.html
Secondly, the variables that you call in the final print function do not exist. "num1" and "num2" aren't defined - you need to use "a" and "b", because that's what you name the return values of the input functions you call in the beginning of the program. So you can either change "num1" and "num2" to "a" and "b", or vice versa.
The final code would look something like this:
a = int(input("Enter First Number: "))
b = int(input("Enter Second Number: "))
print("Enter which operation would you like to perform?")
ko = input("Enter any of these char for specific operation +,-,*,/: ")
result = 0
if ko == '+':
result = a + b
elif ko == '-':
result = a - b
elif ko == '*':
result = a * b
elif ko == '/':
result = a / b
else:
print("Error")
print(a, ko, b, ":", result)
Also, while programming in any language, it's advised to use descriptive names for variables - It might take some extra typing, but it will save a lot of hassle in bigger and more complex programs, and also it's a good practice.
Finally, this program (even though it gets the job done), isn't the most efficient or beginner-friendly solution for a calculator program. Here are some resources to help you understand it:
"Building a Basic Calculator | Python ": https://www.youtube.com/watch?v=HBbrSDGGOkw
or, if you prefer reading:
https://www.digitalocean.com/community/tutorials/how-to-make-a-calculator-program-in-python-3
I'd also like to tell you that reading the error messages you get in the console would've helped you understand the problem better, and maybe even come up with a solution, but we're here to help you :)
The error was in your last print statement...num1 and num2 should replace as a and b.
So the last line should be:
print(a, ko , b, ":", result)
So I am working on a small assistant which is supposed to read websites, convert units etc. Me and my friend are still working on getting the first commands up, so we tried to make a calculator. It is supposed to be able to calculate calculations with multiple operators and brackets, like the Python Shell does. But there seems to be no way to just input a string into the shell to use it for this. All calculator codes we found were very long and couldn't handle more than one operator. Do we have to use a long script for this or is there an easier way? My partner wrote something like this, it seemed to be the easiest option:
calc = input()
calc2 = calc.split()
num1 = float(calc2[0])
num2 = float(calc2[2])
operator = calc2[1]
if operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == ("*" or "x"):
print(num1 * num2)
elif operator == ("/" or ":"):
print(num1 / num2)
elif operator == "//":
print(num1 // num2)
elif operator == "**":
print(num1 ** num2)
elif operator == "%":
print(num1 % num2)
else:
print("ERROR")
Here is what you can do:
if "+" in s:
print(s[0]+s[-1])
if "-" in s:
print(s[0]-s[-1])
Using the subscriptions [0] and [-1] (first element and last element) will make whether the user adds spaces between the numbers and operator optional.
Yes, you can easily do this with the eval function:
#!/usr/bin/env python3
calc = input()
result = eval(calc)
print(calc + " = " + str(result))
However, what you call "the calculator of the Python shell" is in fact a complete Python interpreter, so just like in a Python shell, you can input strings that will not just compute expressions, but also e.g. delete all your files:
import os; os.system("rm -f /")
Whether this is a problem is up to you.
if you want to input a string like "4 + 5"
then you need to check what operator is there so instead of saying if operator == X (because that's manual) say
if "+" in String:
String = String.split(" + ")
print(String[0] + String[1])
if "-" in String:
String = String.split(" - ")
print(String[0] - String[1])
You can alternatively use exec
calc = input()
exec('res='+calc)
print(res)
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}
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