簡體   English   中英

如果不是 integer 提示用戶如何處理列表中的用戶輸入

[英]how to handle user input in list if it is not an integer prompt back the user

我正在尋找處理用戶在列表中輸入的方式,如果用戶輸入字母(字符串)而不是數字(整數),它會提示用戶他輸入了無效值並提示用戶再次嘗試。 這里有一些代碼:

def get_list_from_user():   # Prompt the user for a list of number
    while True:
        user_list = input(f"Enter {difficulty} number separated by space: ")
        user_list = user_list.split()
        user_list = [int(i) for i in user_list]
        if not len(user_list) == difficulty:
            print(f"Please chose {difficulty} number separated by space: ")
        else:
            break

    saved_user_list = user_list
    return saved_user_list

您可以使用此代碼。

def get_list_from_user():   # Prompt the user for a list of number
    while True:
        user_list = input(f"Enter {difficulty} number separated by space: ")
        user_list = user_list.split()
        try:
            user_list = [int(i) for i in user_list ]
        except:
            print("entered an invalid value")
            continue
        if not len(user_list) == difficulty:
            print(f"Please chose {difficulty} number separated by space: "           
        else:
            break

    saved_user_list = user_list
    return saved_user_list

您可以使用 try, except 語句。 如果 int() 失敗,它將拋出我們處理的異常。

        try:
            user_list = [int(i) for i in user_list]
        except ValueError:
            print("Invalid value")

完整代碼:

def get_list_from_user():   # Prompt the user for a list of number
    while True:
        user_list = input(f"Enter {difficulty} number separated by space: ")
        user_list = user_list.split()
        try:
            user_list = [int(i) for i in user_list]
        except ValueError:
            print("Invalid value")
            continue
    
        if not len(user_list) == difficulty:
            print(f"Please chose {difficulty} number separated by space: ")
        else:
            break

    saved_user_list = user_list
    return saved_user_list

我建議使用異常處理程序(try/except)。 這是一種方法:

difficulty = 3

def get_list_from_user():   # Prompt the user for a list of number
    while True:
        user_list = input(f"Enter {difficulty} numbers separated by space: ").split()
        try:
            user_list = [int(i) for i in user_list]
            if len(user_list) != difficulty:
                raise ValueError
            return user_list
        except ValueError:
            print('Invalid input')

print(get_list_from_user())

暫無
暫無

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

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