gpt4 book ai didi

python - 基本计算器只会添加值

转载 作者:行者123 更新时间:2023-12-01 07:53:13 24 4
gpt4 key购买 nike

我是Python新手,正在尝试制作一个基本计算器,它接受两个数字并执行用户指定的操作,但无论我输入什么操作,数字总是相加。

num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = input("Type Add, Subtract, Multiply, or Divide" )

if operation == "Add" or "add":
add = num1 + num2
print(add)
elif operation == "Subtract" or "subtract":
sub = num1 - num2
print(sub)
elif operation == "Multiply" or "multiply":
mult = num1 * num2
print(mult)
elif operation == "Divide" or "divide":
div = num1 / num2
print(div)
else:
print("Enter a valid operation: ")

根据我所拥有的,如果 num1 = 10 且 num2 = 5 并且我输入“乘”,我得到的结果是 15,而不是 50。

最佳答案

if operation == "Add" or "add"

这是两个条件:

  1. if 操作 == "Add" 它将执行您所期望的操作。
  2. if "add" - 始终计算为 True,因为它是常量字符串。所以你也可以这样写:如果为真。您需要将其替换为:
if operation == "Add" or operation == "add"

无论如何,我想提出一些建议。

小写,然后仅检查一次

您应该小写输入字符串,而不是仔细检查“Add”或“add”:

num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = input("Type Add, Subtract, Multiply, or Divide" ).lower() # Notice the `lower` here

if operation == "add":
add = num1 + num2
print(add)
elif operation == "subtract":
sub = num1 - num2
print(sub)
elif operation "multiply":
mult = num1 * num2
print(mult)
elif operation "divide":
div = num1 / num2
print(div)
else:
print("Enter a valid operation: ")

使用内置 operator模块

operator 模块恰好包含您需要的方法。为了方便起见,您可以使用它(尚未测试,应该有效):


import operator
keywords = {"add": "add", "subtract": "sub", "multiply": "mul", "divide": "truediv"}

num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = input("Type Add, Subtract, Multiply, or Divide" )
op_func = keywords.get(operation.lower(), "add") # defaults to add
print(getattr(operator, op_func)(num1, num2))

关于python - 基本计算器只会添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56096557/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com