python-3.x - Python Synthax 错误:使用 Elifs 的语法无效
问题描述
我正在为学校期末项目设计一个计算器。我对 Python 很陌生,不知道为什么我的 Elifs 有 SyntaxError: invalid syntax。我也很感激打印带有 2 个小数点的浮点数的帮助,因为我非常不确定如何使用它。谢谢!
# This is a calculator that calculates Addition, Subtraction, Division, Multiplication and Powers.
# It must round all answers to atleast 2 decimal points.
print ("Welcome! Choose what Type of operation you would like, 1: Addition, 2: Subtraction, 3: Multiplication, 4: Division, 5: Powers.")
Choice = int(input("Your Choice ( 1 - 5 ): "))
if Choice <= 0 or Choice > 5:
print ("Invalid Entry")
elif Choice == 1 or Choice == 2 or Choice == 3 or Choice == 4 or Choice == 5:
num1 = float(input("Your First Number: "))
num2 = float(input("Your Second Number: "))
if Choice == 1:
Addition = num1 + num2
print ("Your Final Number Is: " + str(round(Addition, 2))
elif Choice == 2:
Subtraction = num1 - num2
print ("Your Final Number Is: " + str(round(Subtraction, 2))
elif Choice == 3:
Multiplication = num1 * num2
print ("Your Final Number Is: " + str(round(Multiplication, 2))
elif Choice == 4:
Division = num1 / num2
print ("Your Final Number Is: " + str(round(Division, 2))
elif Choice == 5:
Powers =num1 / num2
print ("Your Final Number Is: " + str(round(Powers, 2))
else:
print ("Invalid Entry")
解决方案
问题是您的打印报表。在这些中,您打开 print ,(
然后打开 str ,(
然后打开 round ,(
然后关闭 round)
并关闭 str ,)
但不要关闭 print 语句)
。所以你有 3(
但只有 2)
所以你需要在)
打印行的末尾添加以关闭语句。
但是,如果您发现自己像打印报表一样重复您的代码,那么可能有更好的方法来做到这一点。下面只是一个示例,说明如何以更简洁的方式编写它
# This is a calculator that calculates Addition, Subtraction, Division, Multiplication and Powers.
# It must round all answers to atleast 2 decimal points.
print("Welcome! Choose what Type of operation you would like, 1: Addition, 2: Subtraction, 3: Multiplication, 4: Division, 5: Powers.")
Choice = int(input("Your Choice ( 1 - 5 ): "))
if 1 <= Choice <= 5:
num1 = float(input("Your First Number: "))
num2 = float(input("Your Second Number: "))
result = 0
if Choice == 1:
result = num1 + num2
elif Choice == 2:
result = num1 - num2
elif Choice == 3:
result = num1 * num2
elif Choice == 4:
result = num1 / num2
elif Choice == 5:
result = num1 ** num2
print("Your Final Number Is: " + str(round(result, 2)))
else:
print("Invalid Entry")
推荐阅读
- angular - 量角器在 Angular 12 中是否已弃用?
- java - 能够捕获用户输入字符串的数字和符号
- android - 在android中使用所有文件访问权限有多好?
- flutter - 如何在 Flutter 中的文本末尾添加图标按钮?
- flutter - 没有为类“BasicMessageChannel”定义方法“setMockMessageHandler”
' - apache-spark - Spark 应用程序在接受状态很长时间后失败。日志说 Socket 超时异常
- c# - 每当我尝试运行时,ProGrids 错误消息都会冻结 Unity 应用程序
- python - 在数据砖(python)中安装后如何获取azure blob的最后修改日期?
- c++ - 使用 ctrl + z 结束读取 C++ 中的字符数组
- reactjs - 条件逻辑反应原生“文本字符串必须在
零件。”