![](/img/trans.png)
[英]Comparing user inputs to items within a list taken from a column of a database (Python3/SQL)
[英]Asking for a sequence of inputs from user python3
我正在进行一个python练习,要求编写可读取整数输入序列并打印的Write 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函数。
我的问题是我如何要求用户提供多个输入,直到他们决定不再添加任何输入。 谢谢你的时间。
您可以在完成时让用户标记。 ( 现场示例 )
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
的初始值不同in_num
。
顺便说一句,您应该添加逻辑来处理错误的输入(即不是整数),以避免运行时异常。
在此特定示例中,您可能还想创建smallest
和largest
变量,并在每次输入后计算它们的值。 很小的计算并不重要,但是当您移至更大的项目时,您将需要牢记代码的效率。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.