【问题标题】:Why doesn't it work I'm trying to make a simple calculator为什么它不起作用我正在尝试制作一个简单的计算器
【发布时间】:2022-12-03 09:52:05
【问题描述】:
def add(a, b):
return a + b
print("choose 1 to add and 2 to subtract")
select = input("enter choice 1/2")
a = float(input("enter 1st nunber: "))
b = float(input("enter 2nd number: "))
if select == 1:
print(a, "+", b, "=", add(a, b))
我不知道为什么它不想添加
【问题讨论】:
标签:
python
python-3.x
calculator
【解决方案1】:
您可以使用 f string 在 print 语句中打印变量的值:
def add(a, b):
return a + b
print("choose 1 to add and 2 to subtract")
select = int(input("enter choice 1/2: "))
a = float(input("enter 1st nunber: "))
b = float(input("enter 2nd number: "))
if select == 1:
print(f"{a} + {b} = {add(a, b)}")
输出:
choose 1 to add and 2 to subtract
enter choice 1/2: 1
enter 1st nunber: 21
enter 2nd number: 3
21.0 + 3.0 = 24.0
【解决方案2】:
您需要将 select 转换为 int
def add(a, b):
return a + b
print("choose 1 to add and 2 to subtract")
select = int(input("enter choice 1/2"))
a = float(input("enter 1st nunber: "))
b = float(input("enter 2nd number: "))
if select == 1:
print(a, "+", b, "=", add(a, b))