我是编程并开始学习Python的新手。我做了一个简单的计算器作为练习,因为语法错误而运行我的代码存在问题。你能说出我犯错的地方:
while True:
print("Options:")
print("Enter 'add' to add two numbers")
print("Enter 'substract' to substract two numbers")
print("Enter 'multiply' to multiply two numbers")
print("Enter 'divide' to divide two numbers")
print("Enter 'quit' to end the program")
user_input = input(":")
if user_input == "quit":
break
elif user_input == "add":
...
elif user_input == "substract":
...
elif user_input == "multiply":
...
elif user_input == "divide":
...
else:
print("Unknown input")
elif user_input == "add":
num1 = float(input("Enter a number:"))
num2 = float(input("Enter another number:"))
result = str(num1 + num2)
print("The answer is:" + result)
elif user_input == "substract":
num1 = float(input("Enter a number:"))
num2 = float(input("Enter another number:"))
result = str(num1 - num2)
print("The answer is:" + result)
elif user_input == "multiply":
num1 = float(input("Enter a number:"))
num2 = float(input("Enter another number:"))
result = str(num1 * num2)
print("The answer is:" + result)
elif user_input == "divide":
num1 = float(input("Enter a number;"))
num2 = float(input("Enter another number:"))
result = str(num1 / num2)
print("The answer is:" + result)
感谢您以后的反馈!
答案 0 :(得分:1)
因为你的第二个elif语句是在else语句之后。
我还添加了一个try
和execpt
块的示例来处理ZeroDivisionError
while True:
print("Options:")
print("Enter 'add' to add two numbers")
print("Enter 'substract' to substract two numbers")
print("Enter 'multiply' to multiply two numbers")
print("Enter 'divide' to divide two numbers")
print("Enter 'quit' to end the program")
user_input = input(":")
if user_input == "quit":
break
elif user_input == "add":
num1 = float(input("Enter a number:"))
num2 = float(input("Enter another number:"))
result = str(num1 + num2)
print("The answer is:" + result)
elif user_input == "substract":
num1 = float(input("Enter a number:"))
num2 = float(input("Enter another number:"))
result = str(num1 - num2)
print("The answer is:" + result)
elif user_input == "multiply":
num1 = float(input("Enter a number:"))
num2 = float(input("Enter another number:"))
result = str(num1 * num2)
print("The answer is:" + result)
elif user_input == "divide":
num1 = float(input("Enter a number;"))
num2 = float(input("Enter another number:"))
# Example of a Try/Catch block to avoid ZeroDivisionError
try:
result = str(num1 / num2)
print("The answer is:" + result)
except ZeroDivisionError:
print("Can't divide by 0")
else:
print("Unknown input")