当我执行并运行代码时,程序似乎不存储c输入,因此不会继续执行其余计算器功能的代码。
def calc():
print("Press 1 for addition")
print("Press 2 for subtraction")
print("Press 3 for multiplication")
print("Press 4 for division")
c = input()
if c == 1:
print("Enter a number")
x = input()
print("Enter another number")
y = input()
return x + y
elif c == 2:
print("Enter a number")
x = input()
print("Enter another number")
y = input()
return x - y
elif c == 3:
print("Enter a number")
x = input()
print("Enter another number")
y = input()
return x * y
elif c == 4:
print("Enter a number")
x = input()
print("Enter another number")
y = input()
return x / y
calc()
我现在已经对代码进行了改进,但似乎无法正确缩进,似乎正在执行的每种数学类型的返回函数都是“外部函数”
def calc():
print("Press 1 for addition")
print("Press 2 for subtraction")
print("Press 3 for multiplication")
print("Press 4 for division")
c = int(input())
def get_inputs():
print("Enter a number")
x = int(input())
print("Enter another number")
y = int(input())
return x, y
if c == 1:
x, y = get_inputs()
return x + y #These return functions seem to be an error
elif c == 2:
x, y = get_inputs()
return x - y
elif c == 3:
x, y = get_inputs()
return x * y
elif c == 4:
x, y = get_inputs()
return x / y
calc()
答案 0 :(得分:0)
input()
与Python 2.7中的raw_input()
相同,后者返回str
类型的对象。您需要明确地将其强制转换为int
c = int(input())
答案 1 :(得分:0)
首先,使用c = int(input())
代替将输入字符串转换为整数。
另外,为了使程序更清洁,因为您已经在使用函数(calc
),所以也可以将每个操作的输入部分放在函数中:
def get_inputs():
print("Enter a number")
x = int(input())
print("Enter another number")
y = int(input())
return x, y
然后为每个操作执行以下操作:
if c == 1:
a, b = get_inputs()
return a + b
(编辑)试试这个:
def get_inputs():
print("Enter a number")
x = int(input())
print("Enter another number")
y = int(input())
return x, y
def calc():
print("Press 1 for addition")
print("Press 2 for subtraction")
print("Press 3 for multiplication")
print("Press 4 for division")
c = int(input())
if c == 1:
x, y = get_inputs()
return x + y
elif c == 2:
x, y = get_inputs()
return x - y
elif c == 3:
x, y = get_inputs()
return x * y
elif c == 4:
x, y = get_inputs()
return x / y
calc()