簡體   English   中英

在用戶停止之前,我如何要求用戶輸入?

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

問題
編寫一個程序,將一個整數列表讀入一個列表,只要整數大於零,然后輸出列表中最小和最大的整數。

例如:如果輸入是:
10
5
3
21
2
-6(負六,stackoverflow 上的格式很奇怪)

output 是:
2
21

您可以假設整數列表至少有 2 個值。

我的代碼

lst =[]

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

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

問題
我的代碼對於有 6 個輸入的示例輸入非常有效。 但是,對於不同數量的輸入(例如 4 個輸入或 9 個輸入),范圍(6)是有限的,並且不會產生我想要的 output。 我只是不知道當問題沒有指定它將接受的輸入數量時,我應該如何確定詢問輸入的范圍。

幫助后的代碼

lst =[]

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

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

你可以while操作while break

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

或者,如果您使用 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))

如果您想要一個更靈活的程序以實現未來的可擴展性,您可以實現一個生成器 function 用於列表理解。 可能看起來像這樣的一個例子是:

# 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()

我繼續輸入提示代碼以便更好地理解。 此外, int_input_generator處理輸入不是數字的情況。

注意:我選擇使用正則表達式進行數字驗證,因為str.isnumeric()str.isdecimal()str.isdigit()等函數允許某些不是典型 ASCII 數字的 unicode 字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM