首页 文章

询问用户python3的一系列输入

提问于
浏览
0

我正在进行python练习,要求编写Python程序,读取一系列整数输入和打印

The smallest and largest of the inputs.

我的代码到目前为止

def smallAndLarge():

    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter a number: "))

    if num1 > num2:
        print(num1,"is the largest number, while",num2,"is the smallest number.")
    else:
        print(num2,"is the largest number, while",num1,"is the smallest number.")


smallAndLarge()

我正在使用def smallAndlarge():因为我的导师希望我们将来为所有程序使用def函数 .

我的问题是如何在用户决定不再添加输入之前询问用户的多个输入 . 谢谢你的时间 .

1 回答

  • 1

    您可以在完成后让用户标记 . (live example

    numbers = [];
    in_num = None
    
    while (in_num != ""):
        in_num = input("Please enter a number (leave blank to finish): ")
        try:
            numbers.append(int(in_num))
        except:
            if in_num != "":
                print(in_num + " is not a number. Try again.")
    
    # Calculate largest and smallest here.
    

    您可以为"stop"选择任何字符串,只要它与 in_num 的初始值不同即可 .

    顺便说一句,您应该添加逻辑来处理错误输入(即不是整数)以避免运行时异常 .

    在此特定示例中,您可能还想创建 smallestlargest 变量,并在每次输入后计算它们的值 . 不要't matter so much for a small calculation, but as you move to bigger projects, you'想要保持代码的效率 .

相关问题