我觉得这个问题的措辞不够好,但这才是我真正想要的:
我正在将这段代码写在一个用户'可以根据需要输入1到10的整数。每次用户输入整数后,使用是/否类型问题询问他/她是否想要输入另一个。计算并显示列表中整数的平均值。
不是'而'应该一遍又一遍地运行部分程序,直到它被告知不要停止?
num_list = []
len()
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
while integer_pushed < 0 or integer_pushed > 10:
print('You must type in an integer between 0 and 10')
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
while again == "y":
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
print ("Number list:", num_list)
while again == "y":
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
print ("Number list:", num_list)
即使用户输入“&#39;”,它也会在第二次停止后停止。然后它给我一个数字列表:&#34;。
再一次,你们一直很好地协助我的同学和我。我在Python课程的介绍中,我们正在学习循环和列表。
答案 0 :(得分:0)
试试这个:
num_list = []
again = "y"
while again == "y":
try:
integer_pushed = float(input("Enter as many integers from 1 to 10"))
if integer_pushed > 0 or integer_pushed <= 10:
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
print("Number list:", num_list)
else:
print('You must type in an integer between 0 and 10')
except ValueError:
print('You must type in an integer not a str')
我不确定为什么你有两个不同的while循环,更不用说三个了。但是,这应该做你想要的。它将提示用户输入一个数字,并尝试将其转换为浮点数。如果无法转换,则会再次提示用户。如果它被转换,它将检查它是否在0到10之间,如果是,它将把它添加到列表中,否则,它会告诉用户这是一个无效的数字。< / p>
答案 1 :(得分:0)
一个while
循环足以实现您的目标。
num_list = []
again = 'y'
while again=='y':
no = int(input("Enter a number between 1 and 10: "))
if not 1 <= no <= 10:
continue
num_list.append(no)
again = input("Enter another? [y/n]: ")
print("Average: ", sum(num_list) / len(num_list))
while
循环的运行时间与again == 'y'
一样长。如果用户输入的整数不在1到10之间,程序会询问另一个数字。