Home > Software design >  Mathematical operation in one single input
Mathematical operation in one single input

Time:11-26

I'm a python beginner and i'm trying to make a calculator that instead of asking the user enter first number than an operator and than antoher number to return the result, the user can be able to input like for example 3 * 3 in one single input so the computer returns 9.

num1 = float(input("Enter a number: "))
op = input("Enter an operator: ")
num2 = float(input("Enter another number: "))

if op == " ":
 print(num1   num2)
elif op == "-":
 print(num1 - num2)
elif op == "*":
 print(num1 * num2)
elif op == "/":
 print(num1 / num2)

else:
 print(" Enter a valid operator...")

CodePudding user response:

IIUC, you are looking to get the complete input from the user in one go, so that your calculator works without asking for inputs 3 times.

NOTE: Using eval is highly unsafe and is very much discouraged. Your approach is absolutely fine and doesn't need eval(). The question you are trying to solve is not related to eval() to begin with. Read more here.

Try this -

num1, op, num2 = input('Enter equation with spaces in-between: ').split(' ')
num1, num2 = float(num1), float(num2)

if op == " ":
    print(num1   num2)
elif op == "-":
    print(num1 - num2)
elif op == "*":
    print(num1 * num2)
elif op == "/":
    print(num1 / num2)

else:
    print(" Enter a valid operator...")
enter equation: 3 * 3
9.0

The str.split(' ') will break the string input into 3 parts based on the spaces. You can then store these in variables, convert the num1 and num2 into float and use your function.

CodePudding user response:

python eval function may help:

inputstr = '3 * 3'
print(eval(inputstr))

CodePudding user response:

If you are sure the input will be completely formatted, use eval()

s = input("Enter an expression: ")
try:
    print(eval(s))
except:
    print("Enter a valid expression...")

CodePudding user response:

As others mentioned, the unsafe way is to use eval(), but a safe way could be

vals = input("Enter an operation: ").split()
num1 = float(vals[0])
op = vals[1]
num2 = float(vals[2])

# The rest of your code as you've written it

CodePudding user response:

Use .split().

This works assuming there's a space separating each value and operator, and there are only two values involved.

def equation():
    string = input("Enter an equation: ")
    #this splits the input string into its parts and puts them into a list
    string_as_list = string.split(' ')
    print(string_as_list)
    
    num1 = float(string_as_list[0])
    op = string_as_list[1]
    num2 = float(string_as_list[2])
    if op == " ":
        result = num1   num2
    elif op == "-":
        result = num1 - num2
    elif op == "*":
        result = num1 * num2
    elif op == "/":
        result = num1 / num2
    
    return result
  • Related