问题:
编写一个函数add_up
,它添加用户提供的整数,在用户写Stop
时停止。
条件:
我的回答:
def add_up():
string = 0
total = 0
while string is not "Stop":
string = int(input())
total += string
print(total)
add_up()
答案 0 :(得分:0)
使用try/except
处理无效输入:
def add_up():
string = 0
total = 0
while True:
string = input()
try:
num = int(string)
total += num
print(total)
except ValueError:
if (string.lower() == "stop"):
print("this ends now!")
break
else:
print("not a number")
add_up()
如果您不想使用try/except
,也可以使用if/else
语句和isidigit()
函数:
def add_up():
string = 0
total = 0
while True:
string = input()
if (string.lower() == "stop"):
print("this ends now!")
break
elif (string.isdigit()):
num = int(string)
total += num
print(total)
else:
print("not a number")
add_up()