Python 如何停止使用字符串处理整数的while循环
我正在处理来自用户的整数输入,希望用户通过键入“q”来表示他们已完成输入,从而表明他们已完成输入 以下是我目前的代码: (还是一个初学者,所以不要过分激怒我)Python 如何停止使用字符串处理整数的while循环,python,list,Python,List,我正在处理来自用户的整数输入,希望用户通过键入“q”来表示他们已完成输入,从而表明他们已完成输入 以下是我目前的代码: (还是一个初学者,所以不要过分激怒我) 任何反馈都是有帮助的 运行该代码时,可能会出现ValueError。这是python告诉您已经将一个值输入到无法处理该类型值的函数中的方式 检查一下 在本例中,您试图将字母“q”输入到第6行预期为int()的函数中。把int()想象成一台只处理整数的机器。你只是想把一封信塞进一台没有处理信件设备的机器里,而不是突然起火,它拒绝了你的输入,
任何反馈都是有帮助的 运行该代码时,可能会出现
ValueError
。这是python告诉您已经将一个值输入到无法处理该类型值的函数中的方式
检查一下
在本例中,您试图将字母“q”输入到第6行预期为int()
的函数中。把int()
想象成一台只处理整数的机器。你只是想把一封信塞进一台没有处理信件设备的机器里,而不是突然起火,它拒绝了你的输入,并开始中断
您可能需要将从str
到int
的转换包装在一个容器中,以处理异常
def main():
num = None
while num != "q":
num = input("Enter number: ")
# try handles exceptions and does something with them
try:
num = int(num)
# if an exception of "ValueError" happens, print out a warning and keep going
except ValueError as e:
print(f'that was not a number: {e}')
pass
# if num looks like an integer
if isinstance (num, (int, float)):
print('got a number')
测试:
我将留给您去弄清楚为什么6.02222“不是一个数字。”尽可能少地更改代码,您应该
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num.append(input("Enter a number: "))
while num[-1] != "q":
num.append(input("Enter a number: "))
count += 1
try:
total += int(num[-1])
except ValueError as e:
print('input not an integer')
break
print (num)
print("The average of the numbers is", total / count)
main()
您可以通过以下方式尝试:
def main():
num_list = [] #list for holding in user inputs
while True:
my_num = input("Please enter some numbers. Type 'q' to quit.")
if my_num != 'q':
num_list.append(int(my_num)) #add user input as integer to holding list as long as it is not 'q'
else: #if user enters 'q'
print(f'The Average of {num_list} is {sum(num_list)/len(num_list)}') #calculate the average of entered numbers by divide the sum of all list elements by the length of list and display the result
break #terminate loop
main()
看看
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num.append(input("Enter a number: "))
while num[-1] != "q":
num.append(input("Enter a number: "))
count += 1
try:
total += int(num[-1])
except ValueError as e:
print('input not an integer')
break
print (num)
print("The average of the numbers is", total / count)
main()
def main():
num_list = [] #list for holding in user inputs
while True:
my_num = input("Please enter some numbers. Type 'q' to quit.")
if my_num != 'q':
num_list.append(int(my_num)) #add user input as integer to holding list as long as it is not 'q'
else: #if user enters 'q'
print(f'The Average of {num_list} is {sum(num_list)/len(num_list)}') #calculate the average of entered numbers by divide the sum of all list elements by the length of list and display the result
break #terminate loop
main()