Создание калькулятора на питоне - PullRequest
0 голосов
/ 24 января 2019

Итак, я попробовал использовать этот кусок кода для создания калькулятора на python, так как я только начал изучать.Дело в том, что он всегда говорит, что я ввел недопустимую опцию, пропуская все мои операторы if-else, даже когда я вхожу в допустимую опцию.Что я сделал не так?

    #!/usr/bin/env python

def add():
    return float(input ("Enter a number: ")) + float(input ("Enter another number: "))

def subt():
    return float(input ("Enter a number: ")) - float(input ("Enter another number: "))

def mult():
    return float(input ("Enter a number: ")) * float(input ("Enter another number: "))

def power():
    return float(input ("Enter a number: ")) ** float(input ("Enter another number: "))

def division():
    return float (input ("Enter a number: ")) / float (input ("Enter another number: "))

s = input("Add, Subtract, Multiply, Divide or Power two Numbers: ")
if s == "add":
    print(add ())
elif s == "subtract":
    print(subt ())
elif s == "multiply":
    print(mult ())
elif s == "power":
    print(power ())
elif s == "division":
    print(division ())
else:
    print ("Enter a valid option")

1 Ответ

0 голосов
/ 24 января 2019

Если звучит так, как будто вы используете Python2.В этом случае используйте raw_input вместо input, в противном случае он пытается найти переменную / функцию с помощью ввода строки пользователя и поместить имя объекта в s.Где raw_input принимает пользовательский ввод в виде строки и помещает строку s.

Это краткий ответ о разнице между ними.

#!/usr/bin/env python

def add():
    return float(input ("Enter a number: ")) + float(input ("Enter another number: "))

def subt():
    return float(input ("Enter a number: ")) - float(input ("Enter another number: "))

def mult():
    return float(input ("Enter a number: ")) * float(input ("Enter another number: "))

def power():
    return float(input ("Enter a number: ")) ** float(input ("Enter another number: "))

def division():
    return float (input ("Enter a number: ")) / float (input ("Enter another number: "))

s = raw_input("Add, Subtract, Multiply, Divide or Power two Numbers: ")
if s == "add":
    print(add())
elif s == "subtract":
    print(subt())
elif s == "multiply":
    print(mult())
elif s == "power":
    print(power())
elif s == "division":
    print(division())
else:
    print("Enter a valid option")

Существует многоразличия в Python2 и Python3, указание того, какой из них вы используете, очень помогает.Когда вы входите в интерпретатор python, он говорит это либо в верхней части вашего терминала, либо при выполнении python --version.

...