要求用户python3进行一系列输入 [英] Asking for a sequence of inputs from user python3
问题描述
我正在进行python练习,要求编写读取一系列整数输入并打印的Python程序
I am working on a python exercise asking for Write Python programs that read a sequence of integer inputs and print
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函数.
I am using def smallAndlarge(): since my instructor wants us to use a def function for all of our programs in the future.
我的问题是我如何要求用户提供多个输入,直到他们决定不再添加任何输入.谢谢您的宝贵时间.
My question is how do I ask for multiple inputs from a user until they decided they dont want to add anymore inputs. Thanks for your time.
推荐答案
您可以在完成时让用户标记.(实时示例)
You could let the user flag when they are finished. (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
的初始值不同即可.
You can choose any string you want for the "stop", as long as it's not the same as the initial value of in_num
.
顺便说一句,您应该添加逻辑来处理错误的输入(即不是整数),以避免运行时异常.
As an aside, you should add logic to handle bad input (i.e. not an integer) to avoid runtime exceptions.
在此特定示例中,您可能还想创建最小
和最大
变量,并在每次输入后计算它们的值.只需很小的计算就没什么关系,但是当您移至更大的项目时,您将需要牢记代码的效率.
In this specific example, you'd also probably want to create smallest
and largest
variables, and calculate their values after each input. Doesn't matter so much for a small calculation, but as you move to bigger projects, you'll want to keep the efficiency of the code in mind.
这篇关于要求用户python3进行一系列输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!