简体   繁体   English

在用户停止之前,我如何要求用户输入?

[英]How do I ask for user input until the user stops?

The Question问题
Write a program that reads a list of integers into a list as long as the integers are greater than zero, then outputs the smallest and largest integers in the list.编写一个程序,将一个整数列表读入一个列表,只要整数大于零,然后输出列表中最小和最大的整数。

Ex: If the input is:例如:如果输入是:
10 10
5 5
3 3
21 21
2 2
-6 (negative six, the format is weird on stackoverflow) -6(负六,stackoverflow 上的格式很奇怪)

the output is: output 是:
2 2
21 21

You can assume that the list of integers will have at least 2 values.您可以假设整数列表至少有 2 个值。

My Code我的代码

lst =[]

for i in range(6):
    if i > 0:
        i = int(input())
        lst.append(i)

print (min(lst), max(lst))

The Problem问题
My code works perfectly well for the example input given where there are 6 inputs.我的代码对于有 6 个输入的示例输入非常有效。 However, for a different number of inputs (such as 4 inputs or 9 inputs), the range(6) is limited and doesn't produce the output that I want.但是,对于不同数量的输入(例如 4 个输入或 9 个输入),范围(6)是有限的,并且不会产生我想要的 output。 I just don't know how I'm supposed to determine the range for asking the input when The Question doesn't specify the number of intputs it will take in.我只是不知道当问题没有指定它将接受的输入数量时,我应该如何确定询问输入的范围。

Code after Help帮助后的代码

lst =[]

while True:
  _input= int(input())
  if _input < 0:
    break
  lst.append(_input)

print(min(lst),max(lst))

You could you while operator and break你可以while操作while break

lst = []
while True:
    _input = int(input())
    if _input < 0:
        break
    lst.append(_input)

Or if you use python3.8 it could be even prettier:或者,如果您使用 python3.8,它可能会更漂亮:

lst = []
while _input := int(input()) >= 0:
    lst.append(_input)
user_num = int(input())
list_num = []

while user_num > 0:
    list_num.append(user_num)
    user_num = int(input())

print(min(list_num),'and',max(list_num))

If you want a more flexible program for future expandability, you can implement a generator function for use in list comprehension.如果您想要一个更灵活的程序以实现未来的可扩展性,您可以实现一个生成器 function 用于列表理解。 An example of what that might look like is this:可能看起来像这样的一个例子是:

# Future imports (needed for certain type hinting functionality)
from __future__ import annotations

# Standard library imports
from re import compile as re_compile
from typing import TYPE_CHECKING

# Type checking (this is False during runtime)
if TYPE_CHECKING:
    from re import Pattern
    from typing import Generator


def int_input_generator() -> Generator[int, None, None]:
    """Integer generator: Stops generating when given incorrect input"""
    numbers_only: Pattern = re_compile(r'^-?[0-9]+$')
    user_input: str
    int_input: int

    while numbers_only.match((user_input := input())) is not None \
            and (int_input := int(user_input)) > 0:
        yield int_input
    return


def main() -> None:
    """Main function to run the program"""
    input_list: list[int] = [_ for _ in int_input_generator()]

    if input_list:
        print(f'{min(input_list)}\n{max(input_list)}')
    return


if __name__ == '__main__':
    main()

I went ahead and type hinted the code for better understanding.我继续输入提示代码以便更好地理解。 Also, the int_input_generator takes care of cases when the input is not a number.此外, int_input_generator处理输入不是数字的情况。

Note: I opted for using regex for numeric validation since functions like str.isnumeric() , str.isdecimal() , and str.isdigit() allow for certain unicode characters that are not the typical ASCII digits.注意:我选择使用正则表达式进行数字验证,因为str.isnumeric()str.isdecimal()str.isdigit()等函数允许某些不是典型 ASCII 数字的 unicode 字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何要求用户输入时间 - How do I ask the user to input time 我如何要求用户输入数字然后存储在文本文件中? - How do I ask user to input numbers to then store in text file? 如何在绘图前要求用户输入日期时间和变量 - how do i ask user for input of datetime & a variable before plotting 如何在输入有效输入之前询问用户特定的字符串和循环? - How to ask the user for a specific string and loop until valid input is entered? 我如何询问用户的输入并在用户键入时分析输入? - How do I ask an input from a user and analyse the input as the user types it? 在需要之前如何停止用户输入? - How do I stop user input until I need it? 如何在 Python 中编写一个 for 循环以反复要求用户输入一个数字,直到他们输入一个整数(0、1、2 等)? - How do I write a for loop in Python to repeatedly ask the user to enter a number until they enter in a whole number (0, 1, 2, etc)? 如何存储元组并继续要求用户输入更多值,直到用户输入“完成”? - How to store tuples and continue to ask the user to input more values until user inputs 'done'? 我如何询问用户姓名,然后检查用户姓名是否正确? - How do I ask user for name then check if it is correct with the user? Python,tkinter:如何在要求用户输入之前显示图像? - Python, tkinter: How do I display an image before I ask for user input?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM