【发布时间】:2015-01-28 19:27:44
【问题描述】:
我正在使用 python 编写计算器的代码。
loop = 1
while loop == 1: #loop calculator while loop is TRUE
print ("""Options:
Addition 1)
Subtraction 2)
Multiplication 3)
Division 4)
Quit 5)
Reset Sum 6) """) #display calculator's options
(' ') #spacer
choice = input("option: ") #get user input for calculator options
#----------------------------------------------------------------------------Addition
if choice == 1: #check if user wants to add
print (' ') #spacer
print ('Addition Loaded!') #tell the user they are adding
print (' ') #spacer
add1 = int(input('Base Number')) #get value for add1
sum = int(input('Number ta add')) #get value for sum
sum = add1 + sum #make sum equal the sum of add1 and sum
print (str(sum)) #print sum
addloop = 1 #set addloop to TRUE
while addloop == 1: #continue addition while addloop = TRUE
add1 = int(input('Additional number to add')) #get value for add1
if add1 == 0: #check if add1 equals zero
print (' ') #spacer
sum = add1 + sum #make sum equal the sum of add1 and sum
if add1 != 0: #check if add1 is not equal to 0
print (str(sum)) #print sum
if add1 == 0: #check if add1 is equal to 0
print ('Total: ',) #print prefix
print (str(sum)) #print sum
addloop = 0 #set addloop to FALSE
在此处列出的加法部分下方,还有其他用于减法、乘法等的部分,它们使用 ELIF 而不是 IF(应该是这样吗?)。问题是,当用户为计算器选择一个选项(加法、减法...)时,它反而会循环回到 while 循环,而不会通过任何 IF 或 ELIF 语句。 IF 语句在 WHILE 循环中不起作用吗?
【问题讨论】:
-
源代码中的每一行都不需要注释,尤其是注释只是重复代码的时候
-
这个问题可能很难弄清楚...
print(choice)似乎显示一个整数...但print(repr(choice))显示它实际上是一个字符串(它永远不等于整数)。 -
@Jasper 我对每一行都进行了评论,以养成做 cmets 的习惯。我不打算在以后评论不必要的行,只是为了帮助我早日学会这样做。
标签: python if-statement while-loop calculator