【问题标题】:Asking for a sequence of inputs from user python3请求用户 python3 的输入序列
【发布时间】:2017-09-26 21:36:08
【问题描述】:

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

我的问题是如何向用户请求多个输入,直到他们决定不再添加输入。感谢您的宝贵时间。

【问题讨论】:

标签: python loops python-3.6


【解决方案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 变量,并在每次输入后计算它们的值。对于小型计算来说并不重要,但是当您转向更大的项目时,您需要牢记代码的效率。

【讨论】:

  • 谢谢你,mac,帮助很大!感谢您的帮助。
  • @Matticus 你打赌!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 2017-07-05
  • 2014-04-08
  • 2021-06-07
  • 1970-01-01
  • 2013-07-03
  • 1970-01-01
相关资源
最近更新 更多