向用户 python3 请求一系列输入

Asking for a sequence of inputs from user python3

我正在做一个 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 函数。

我的问题是,在用户决定不再添加输入之前,我如何要求用户提供多个输入。谢谢你的时间。

您可以让用户在完成后进行标记。 (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 变量,并在每次输入后计算它们的值。对于一个小的计算来说没那么重要,但是当你转向更大的项目时,你会想要记住代码的效率。