【问题标题】:My while loop should be running until the user wants to stop it but ends after the 2nd input我的 while 循环应该一直运行,直到用户想要停止它但在第二次输入之后结束
【发布时间】:2018-07-18 06:25:37
【问题描述】:

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

我正在编写这段代码,其中“用户”可以根据需要输入从 1 到 10 的整数。每次用户输入一个整数后,使用是/否类型的问题来询问他/她是否要输入另一个整数。计算并显示列表中整数的平均值。

'while' 不应该一遍又一遍地运行程序的一部分,直到它被告知不要停止时才停止?

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”,它也会在第二次之后停止。然后它给了我“号码列表:”。

再一次,你们为我和我的同学们提供了很好的帮助。我正在学习 Python 课程,我们正在学习循环和列表。

【问题讨论】:

  • 为什么while again == 'y': 循环重复了两次?
  • 另外这段代码似乎对我有用

标签: python input while-loop append


【解决方案1】:

试试这个:

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 之间,如果是,它将把它添加到列表中,否则,它会告诉用户这是一个无效的数字。

【讨论】:

    【解决方案2】:

    一个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 之间,程序会要求输入另一个数字。

    【讨论】:

    • 我真的很喜欢这段代码,因为您向我展示了我需要一个“while”来循环和循环,直到用户说“n”。真的很容易理解,你真的清理了我的垃圾代码。非常感谢尼西莫氧化物
    猜你喜欢
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多