我正在创建一个(非常粗糙的)计算器,想知道这段代码有什么问题


# Pick the numbers you'd like to use
number1 = (input('What is the first number?n'))
number2 = (input('What is the second number?n'))
# Choose what to do with those numbers
Choice = input('Would you like to add, subtract, multiply or divide?n ')
# Where the calculating happens, if it doesn't go through the error message asking you to use numbers will happen
try :
# Converting the numbers from str into float, if this doesnt happen it means numbers were not used
num1 = float(number1)
num2 = float(number2)
if Choice is add :
answer = num1 + num2
elif Choice is subtract : 
answer = num1 - num2
elif Choice is divide :
answer = num1/num2
elif Choice is multiply
answer = num1 * num2
print(answer)
# The error message if the numbers you gave werent in numeric form
except :
print('Please choose proper numbers in numeric form instead of letter/words')
这是代码,我得到的问题是:

File "main.py",第13行选择减法:^SyntaxError: invalid syntax

任何帮助将不胜感激,谢谢:)。(如果这段代码根本不起作用,请原谅。我目前正在阅读一本关于如何编码的书,我认为这将是一个有趣的尝试,因为我刚刚学习了布尔值和变量)

我想你是这个意思:

if Choice == 'add':
answer = num1 + num2
elif Choice == 'subtract': 
answer = num1 - num2
elif Choice == 'divide':
answer = num1/num2
elif Choice == 'multiply':
answer = num1 * num2

小心缩进。如果你有一个单独的If/elseif/elseif/elseif/else链,每个条件应该在相同的缩进级别,每个主体应该匹配它的条件加一个缩进(通常是4个空格或1个制表符)。

要比较从具有input()的用户捕获的字符串与文字字符串,您可以这样做:

if Choice == 'add':

您需要在'add'周围指定引号,否则它将尝试引用一个未定义的名为add的变量。

对于==is在检查字符串时,请参见为什么使用'=='或& # 39;如果# 39;有时会产生不同的结果?

相关内容

最新更新