【发布时间】:2015-03-27 17:06:58
【问题描述】:
我正在尝试制作一个简单的加法计算器,但遇到了问题。
print('welcome to calculator') # Print opening message
print(' ') #Spacer
int(sum1) = input('number') # Get input for first number, this variable later becomes the sum : ERROR: Can't assign to function call
int(add1) = input('number') # Get input for second number : Assumed error for this line as well
sum1 = sum1 + add1 # Add the variables together to get the sum
print(str(sum1)) # Change the sum to a string and print it
loop = 1 # Set loop to True
while loop == 1: # Continue the program until user inputs add1 as '0'
int(add1) = input('number') # Get value for add1
if add1 == 0: # Stop the program when add1 is equal to 0
loop = 0 # Set loop to false
break
sum1 = sum1 + add1 # Add the variables together to get the new sum
print(str(sum1)) # Change the sum to a string and print it
print('done!') # Print ending message
这里的错误在第三行(我假设第四行也会有错误)。我本来只是有
sum1 = input('number')
但是变量 sum1 被视为一个字符串,所以在第 5 行中,当变量 sum1 和 add1 被添加时,它会将字符串添加到彼此的末尾。 (例如:15 + 10 = 1510)
当我将变量转换为整数时我做错了什么,或者这是解决问题的错误方法?
【问题讨论】:
-
这是 Python 2 还是 Python 3?如果是 python 2,你应该使用
raw_input()而不是input()。
标签: python string variables integer calculator