João Teixeira
João Teixeira

Reputation: 31

Quick calculator with a single input statement

I am trying to make a quick test calculator that get's all the operation in a single line and a single input statement, but it is giving me a Could not convert string to float error

x = input("Calculadora\nEnter the operation: \n")
y = float(x[0])
z = x[1]
w = float(x[2])
print(y + w)
if z == '+':
    s = y + w
    print(s)

Upvotes: 2

Views: 139

Answers (2)

kederrac
kederrac

Reputation: 17322

For any kind of numbers in your input (negative numbers or floats) you can use:

x = input("Calculadora\nEnter the operation: \n")
print(eval(x))

If you want to be 100% safety with the user input you can use literal_eval from ast module

from ast import literal_eval
print(literal_eval(x)) 

Upvotes: 1

enzo
enzo

Reputation: 11486

You can use split method for string.

x = input().split('+')
num1 = float(x[0])
num2 = float(x[1])
print(num1 + num2)

Of course you can extend this for others operators.

Upvotes: 1

Related Questions