我的WARE循环应该运行,直到用户想停止它,但在第二个输入之后结束



我觉得这个问题的措辞不是很好,但这是我真正想要的:

我正在编写此代码,其中"用户"可以按照他/她想要的时间从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)

即使用户在'y'中键入,它也会在第二次停止。然后,它给了我"数字列表:"。

再次,你们在协助我的同学和我的I中很棒。

一个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之间的整数。

尝试以下:

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')

我不确定为什么在循环时有两个不同,更不用说三个了。但是,这应该做您想要的。它将提示用户获取一个数字,并尝试将其转换为浮点。如果无法转换,它将再次提示用户。如果已转换它将检查是否在0到10之间,如果是的,则将其添加到列表中,否则,它将告诉用户这是一个无效的数字。

相关内容

最新更新