I am creating a game in python where I need to run basic math operations. These operations would be provided by a user as input. How do I do this?
So far, I have independent variables for each number and each operator, however, when I run the code, it does not recognize the operator ('+','-','*','/') as an operator, but rather as strings. Therefore, when running the programming it would run as 1'+'1.
print("Now you can solve it. ")
vinput1=int(input("Please input the first number"))
print("First number is recorded as", vinput1)
vop1=input("Please input your first operator")
print("Your operator is recorded as", vop1)
vinput2=int(input("Please input the second number"))
print("Second number is recorded as", vinput2)
vsofar = (vinput1, vop1, vinput2)
print(vsofar)
Computer's output:
(1, '+', 1)
While eval operates in a very general context and so much scope for introducing security issues ast.literal_eval is intended to evaluate string literals only and so has a far narrower and hence safer scope.
from ast import literal_eval
print("Now you can solve it. ")
vinput1=int(input("Please input the first number"))
print("First number is recorded as", vinput1)
vop1=input("Please input your first operator")
print("Your operator is recorded as", vop1)
vinput2=int(input("Please input the second number"))
print("Second number is recorded as", vinput2)
vsofar = (vinput1, vop1, vinput2)
print(literal_eval(''.join(map(str, vsofar))))
Otherwise create a mapping from operators to functions to lookup the function to call for each operator.
import operator
import sys
ops = {'+': operator.add,
'-': operator.sub}
v1 = int(input('enter first num'))
op1 = input('input operator')
if not op1 in ops:
print('unsupported operation')
sys.exit(1)
v2 = int(input('enter second num'))
print(ops[op1](v1, v2))
The great thing about this is that you don't have to screw around in the program logic to add new (binary) operations. You just add them to the dict, with far less opportunity to make a typo in a long if/elif chain.
The safest and simplest method is to use an if-statement to check which symbol was input. A sample if-statement would be:
print("Now you can solve it. ")
vinput1=int(input("Please input the first number"))
print("First number is recorded as", vinput1)
vop1=input("Please input your first operator")
print("Your operator is recorded as", vop1)
vinput2=int(input("Please input the second number"))
print("Second number is recorded as", vinput2)
if (vop1 == "-"):
vsofar = vinput1 - vinput2
print(vsofar)
elif (vop1 == "+"):
vsofar = vinput1 + vinput2
print(vsofar)
elif (vop1 == "/"):
vsofar = vinput1 / vinput2
print(vsofar)
elif (vop1 == "*"):
vsofar = vinput1 * vinput2
print(vsofar)
else
print("Invalid operator entered.")
Just to quickly explain, these if-statements check whether the operator entered, which is stored in vop1, matches the -, +, *, or / operator. If it matches any of these, then its respective operation is carried out and stored in the variable vsofar,cwhich is printed in the line after that operation. If none of the operations work, then an invalid statement is printed.
This is the most bland, simple, and somewhat long way of doing it. However, the eval() function is not safe to use. A shorter yet more complex than my way is the answer of Paul Rooney.
Hope this helps!
You Can evaluate!
>>> input1=1
>>> input2=3
>>> vop1="+"
>>> print eval(str(input1)+vop1+str(input2))
4
Have a look at this
Hope this helps!
If you don't want to use eval() you might try a series of conditionals to test the operator and then perform the correct calculation based on that.
if vop1 == "+":
return vinput1 + vinput2
if vop1 == "-":
return vinput1 - vinput2
num1= int(input("first number: "))
num2= int(input("2md number: "))
sign= input("sign operator: ")
if sign == '+':
print("Answer is", num1+num2)
elif sign == '-':
print("Answer is", num1-num2)
elif sign == '*':`enter code here
print("Answer is", num1*num2)
elif sign == '/':
print("Answer is", num1/num2)
else:
print("am not built to use this sign yet")
Related
first project beginner here! I just finished my first project, a somewhat working calculator i know it is not that great but as i said beginner. I would like to limit the options for number = input meaning if you write anything else than add,substract,divide or multiply you receive an error like " please try again" and afterwards the programm is restarted
Help very much appreciated Thank you.
list = ("add", "substract", "divide" , "multiply" )
number = input("do you want to add substract divide or multiply? ")
if number in list:
print("ok")
else:
print("try again")
number_one = float(input("enter your first number "))
number_two = float(input("enter your second number "))
if number == "add":
solution_one = number_one + number_two
print(solution_one)
if number == "substract":
solution_two = number_one - number_two
print(solution_two)
if number == "divide":
solution_three = number_one / number_two
print(solution_three)
if number == "multiply":
solution_four = number_one * number_two
print(solution_four)
i could only find solutions regarding while loops but i did not know how to use them in this case as these weren't strings but integers.
The fact that you're prompting for a string doesn't change the way the while loop works. Run your code in a loop and break when it's time for the loop to end.
while True:
number = input("do you want to add substract divide or multiply? ")
if number in ("add", "substract", "divide" , "multiply" ):
print("ok")
break
print("try again")
Note that it's considered bad practice to give a variable a name like list (or any other built-in name) since it can lead to very confusing bugs when you try to reference the built-in name later!
You could consider using the operator module.
Build a dictionary that maps the user's selected operation with the relevant function.
import operator
OMAP = {
'add': operator.add,
'subtract': operator.sub,
'divide': operator.truediv,
'multiply': operator.mul
}
while (op := input('Do you want to add, subtract, multiply, divide or end? ')) != 'end':
try:
if (func := OMAP.get(op)):
x = float(input('Enter your first number: '))
y = float(input('Enter your second number: '))
print(func(x, y))
else:
raise ValueError(f'"{op}" is not a valid choice')
except ValueError as e:
print(e)
The code uses operator that was chosen in the previous play even after choosing a different operator after opting to play again.
I've checked the functions again and still can't find where exactly the problem is.
import random
print "Welcome!"
def get_choice():
print "What are we practicing? \n1. Addition (+) \n2. Subtraction (-) \n3. Multiplication (*) \n4. Division (/)"
option = raw_input('> ')
while option != '+' and option != '-' and option != '*' and option != '/':
print "You typed %r which is not valid. Please enter \'+, -, *,or /\'" %(option)
option = raw_input('>')
return option
operation = get_choice()
def ask_question (operation):
numbers = []
for y in range(0,2):
x = random.randint(1,100)
numbers.append(x)
num1 = numbers[0]
num2 = numbers[1]
print num1, operation, num2
response = int(raw_input('>'))
return num1, num2, response
num1, num2, response = ask_question(operation)
def check_response(response):
if operation == '+':
answer = num1 + num2
elif operation == '-':
answer = num1 - num2
elif operation == '*':
answer = num1 * num2
else:
answer = num1 / num2
i = 0
if response == answer:
print "Correct!"
elif response != answer:
while i < 2:
print "Wrong! Try again: \n%r + %r" %(num1, num2)
i += 1
response = raw_input()
if response != answer and i >= 2:
print "Sorry. You run out of chances."
check_response(response)
def repeat():
while True:
print "Do you want to play again?"
again = raw_input('>')
if again == 'y' or again == 'Y':
get_choice()
ask_question(operation)
check_response(response)
else:
break
repeat()
Welcome! What are we practicing?
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
*
18 * 4
72 Correct! Do you want to play again?
y
What are we practicing?
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
+
94 * 83
The reason it gets stuck on one operation is you are not catching any return value from get_choice() when you call it within repeat(). I adjusted the raw_input() to input() so I could get it to work (I'm on python 3.X, and you should upgrade also since 2.X will be discontinued this year!), and it seems to work fine for me now:
def repeat():
while True:
print("Do you want to play again?")
again = input('>')
if again == 'y' or again == 'Y':
operation = get_choice() # you need to assign "operator" to the return value
ask_question(operation)
check_response(response)
else:
break
repeat()
Sample output:
Welcome!
What are we practicing?
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
> +
82 + 72
>154
Correct!
Do you want to play again?
>y
What are we practicing?
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
> -
57 - 28 # the sign did in fact change to -
>
I'm trying to practice python because I'm starting yr 12 soon. I created a quiz game but when i get the question right it always says that it's wrong
print("Welcome to the math quiz game!")
for i in range(0,10):
operators = ['+','-','*','/']
import random
num1 = random.randint(1,10)
num2 = random.randint(1,10)
randop = random.choice(operators)
question = input("What is %d %s %d: " % (num1,randop,num2))
if randop == "+":
answer = num1 + num2
elif randop == "-":
answer = num1 - num2
elif randop == "*":
answer = num1 * num2
elif randop == "/":
answer = num1 / num2
if question == answer:
print("\nCorrect")
elif question != answer:
print("Incorrect or Invalid")
When doing a comparison in a program with == we must compare two variables of the same type (which can be devious when starting Python). Answer is a number, while question is a string which was written by the user. Thus Python recognizes the two as different and false. To avoid this you must either convert the number to a string or the string to a number so you compare two variables of the same type.
As mentioned you need to cast the return value from input() into an float (to cope with decimals from division):
question = float(input("What is %d %s %d: " % (num1,randop,num2)))
I don't recommend doing this as a bad input will crash the game so use input validation with a try/except block:
question = input("What is %d %s %d: " % (num1,randop,num2))
try:
question = float(question)
except ValueError:
print('Invalid or incorrect.')
continue # skip the rest of the code and head straight into the next iteration in the for loop
Also, I don't recommend including the division option as most values will be recurring decimals which cannot be input correctly unless you check beforehand that the answer will not be recurring or if you round the answer off to, say, 2 decimal places and ask the user for a 2 d.p answer
(You could also make the 'answer' variable a string instead of making 'question' an int)
Am new to Python - have done some scripting in PHP, javascript, but am not a programmer (though am a tech writer with experience documenting APIs etc, so pretty extensive 'passive' programming know how).:
Was following steps here: https://en.wikibooks.org/wiki/A_Beginner's_Python_Tutorial/Functions. Specifically see the link re: simple calculator program
Wanted to figure out if I could make the program less redundant by storing all components for different calculations in list form, then have a very simple, generic means of processing any calculation request, by using the user's menu choice as an index into the list. I'm assuming it's good form to structure things in this way, but don't know! The original tutorial is obviously much more readable, but would mean the same error checking would need to be done repeatedly for each little "if" block...
In any case though, I couldn't figure out how to store the actual calculations as elements within a list. Is that possible? Here's as far as I got... where I managed to encapsulate, and call on, some of the specifics within lists, but had to still do a series of "if" statements for each individual calculation.
(Sorry if these questions are basic.. I did a bunch of searching without finding definitive documentation re: here's everything you can and Cannot capture in list form) So - my variation of the linked-to code:
#simple calculator program
# Prompts for possible calculations
add = ["Add this: ", "to this: ", "+"]
subtract = ["Subtract this: ", "from this: ", "-"]
multiply = ["Multiply this: ", "by this: ", "*"]
divide = ["Divide this: ", "by this: ", "/"]
# List of possible calculations
calcPrompts = [add, subtract, multiply, divide]
def promptEntries(Arg):
try:
op1 = int(input(Arg[0]))
op2 = int(input(Arg[1]))
operator = (Arg[2])
return op1, op2, operator
except:
print("Invalid entry. Please try again.")
choice = 0
#This variable tells the loop whether it should loop or not.
# 1 means loop. Anything else means don't loop.
loop = 1
while loop == 1:
#Display the available options
print ("\n\nCalculator options are:")
print (" ")
print ("1) Addition")
print ("2) Subtraction")
print ("3) Multiplication")
print ("4) Division")
print ("5) Quit calculator.py")
print (" ")
try:
choice = int(input("Choose your option: "))
choice = choice - 1
op1, op2, operator = promptEntries(calcPrompts[choice])
print(op1, operator, op2, "=", end=" ")
if choice == 0:
print(op1 + op2)
elif choice == 1:
print(op1 - op2)
elif choice == 2:
print(op1 * op2)
elif choice == 3:
if op2 != 0:
print(op1 / op2)
else:
print("Division by zero is invalid, please try again.")
elif choice == 4:
loop = 0
print ("Thank you for using calculator.py")
except:
print("invalid entry, please try again.")
In your case, you can use the operators as functions, provided by the operator standard library module.
As you can see, you can assign such functions to a variable, e.g. inserting all of them in a list
import operator as op
f = [op.add,
op.sub,
op.mul,
op.div,
op.pow,
op.mod]
then the loop can become
while True:
#Display the available options
print ("\n\nCalculator options are:")
for i, fun in enumerate(f):
print("{}) {}".format(i+1, fun.__name__))
print ("{}) Quit calculator.py".format(len(f)))
choice = int(input("Choose your option: ")) - 1
if choice == len(f):
print("Thank you for using calculator.py")
break
op1 = int(input("enter operand1: "))
op2 = int(input("enter operand2: "))
try:
result = f[choice](op1, op2)
except IndexError:
print("invalid entry, please try again.")
except ZeroDivisionError:
print("Division by zero is invalid, please try again.")
print('{} {} {} = {}'.format(op1, f[choice].__name__, op2, result))
Note: the example works for dyadic functions only. Further work is needed in case you want to offer a mix of functions with a different number of arguments.
Yes, in python functions are first class objects and you can use them any way that you would use any other object. For example you can have two variables reference the same object:
def myFunction():
pass
newVariable = myFunction
print(newVariable is myFunction)
or reference functions from a list or dictionary:
myList = [myFunction, 1, 2, 3]
print(myList[0] is myFunction)
myDict = {0:myFunction, 1:1}
print(myDict[0] is myFunction)
The above is true for both python's built in functions, functions in the standard library and functions you write. For example:
from operator import add
def countZeros(a):
return sum(item == 0 for item in a)
listOfFunctions = [sum, add, countZeros]
I am trying to create a simple python calculator for an assignment. The basic idea of it is simple and documented all over online, but I am trying to create one where the user actually inputs the operators. So instead of printing 1: addition, 2: subtraction, etc, the user would select + for addition, - for subtraction, etc. I am also trying to make Q or q quit the program.
Any ideas for how to allow the user to type operators to represent the operation?
Note: I know I still need to define my remainder operation.
import math
loop = 1
choice = 0
while loop == 1:
print("your options are:")
print("+ Addition")
print("- Subtraction")
print("* Multiplication")
print("/ Division")
print("% Remainder")
print("Q Quit")
print("***************************")
choice = str(input("Choose your option: "))
if choice == +:
ad1 = float(input("Add this: "))
ad2 = float(input("to this: "))
print(ad1, "+", ad2, "=", ad1 + ad2)
elif choice == -:
su2 = float(input("Subtract this: "))
su1 = float(input("from this: "))
print(su1, "-", su2, "=", su1 - su2)
elif choice == *:
mu1 = float(input("Multiply this: "))
mu2 = float(input("with this: "))
print(mu1, "*", mu2, "=", mu1 * mu2)
elif choice == /:
di1 = float(input("Divide this: "))
di2 = float(input("by this: "))
print(di1, "/", di2, "=", di1 / di2)
elif choice == Q:
loop = 0
print("Thank-you for using calculator")
First off, you don't need to assign choice to zero
Second, you have your code right, but you need to put quotes around the operators in your if statements like this
if choice == '+':
to show that you are checking for a string
make your loop like this:
while 1: #or while True:
#do stuff
elif choice == 'Q': #qoutes around Q
break #use the `break` keyword to end the while loop
then, you don't need to assign loop at the top of your program
You should try replacing if choice == + by if choice == "+".
What you're getting from the input is actually a string, which means it can contain any character, even one that represents an operator.