簡體   English   中英

Python:通過在 function 之外操作變量來驗證用戶輸入

[英]Python:Validating user input by manipulating variable outside of function

我對 python 有點陌生,並且有一個非常基本的了解。

我正在創建一個非常簡單的程序,它可以作為 map 的決定。 用戶輸入 0 表示否,輸入 1 表示是,以便繼續向下判斷 map 並最終得出結論。 對於每個決策,答案(0 或 1)都保存在一個新變量中。

我的問題:我創建了一個 function 來驗證用戶輸入的響應是否有效。 每次我為每個新的決策/變量請求新的響應后,我都想使用這個 function。 例如,在第一個變量seq中,如果用戶輸入 2,則應輸入驗證 function 並進入循環,直到用戶輸入 0 或 1。但是,一旦輸入 0 或 1,我不知道如何將該新值重新分配給seq以繼續執行決定 map。

我嘗試過:將 x 設置為全局,啟動x = 0 ,將變量(即seq )設置為全局,然后添加seq = valid_user_input(x)

任何幫助將不勝感激。 我正在尋找一個簡單的解決方案,希望對我來說不太先進。 這是編輯我的代碼的鏈接! Repl.it map 程序

#Validation Function
def valid_user_input(x):

  while x != 1 and x != 0:
    x = int(input("Please answer the following question with [0 being no] and [1 being yes]\n"))
    print("x value is: ", x)
  return x

#Conditions/ Call Validation Function
seq = int(input("Is your equation in the {An} form or a list of terms?\n0. No]\n[1. Yes]\n"))
valid_user_input(seq) #CALL FUNCTION

if seq == 0: #seq no
  print("You have a series!\n")

  part = int(input("Is your equation in the form Sn?\n[1. Yes]\n[0. No]\n"))
  valid_user_input(part) #CALL FUNCTION

    if part == 0: #part no

    #Continue conditions...

    if part == 1: #part yes

if seq == 1: #seq yes
  print("You have a sequence!")

  tels = int(input("Do all terms cancel out except first and last term?\n[1. Yes]\n[0. No]\n"))
  valid_user_input(tels) #CALL FUNCTION

你設計你的 function 所以它有一個任務:返回 0 或 1 給給定的text (你的問題):

def ask_01(text):
    """Asks text's content until either 0 or 1 are answered and returns that."""
    r = -1
    retry = False
    while r not in {0,1}:
        try:
            if retry:
                print("Wrong input")
            retry = True
            r = int(input(text + " Yes (1) or No (0)?"))
        except ValueError:  # if non-intergers are answered it gets cought here
            pass
    return r

weather_ok = ask_01("Ok Weather?")
happy = ask_01("Are you happy?")
print(weather_ok, happy)

並且只有在輸入有效時才離開 function:

輸入的輸出:4,a,1,3,i,0

Ok Weather? Yes (1) or No (0)? 4
Wrong input
Ok Weather? Yes (1) or No (0)? a
Wrong input
Ok Weather? Yes (1) or No (0)? 1
Are you happy? Yes (1) or No (0)? 3
Wrong input
Are you happy? Yes (1) or No (0)? i
Wrong input
Are you happy? Yes (1) or No (0)? 0

1 0

更多關於驗證:

這是一個人為的例子。 我什至不建議這是做你想要實現的事情的好方法(刪除prompt鍵值對感覺很糟糕) - 我在這里試圖展示的是數據驅動的方法可能是可取的,因為它有助於減少 if 語句。

tree = {

    "prompt": "Do you have a cat (0) or a dog (1)?",

    "0": {
        "prompt": "Is your cat male (0) or female (1)?",
        "0": {"prompt": "You have a male cat!"},
        "1": {"prompt": "You have a female cat!"}
        },
    "1": {
        "prompt": "Is your dog male (0) or female (1)?",
        "0": {"prompt": "You have a male dog!"},
        "1": {"prompt": "You have a female dog!"}
        }

}

current_branch = tree
while True:
    print(current_branch["prompt"])
    del current_branch["prompt"]
    if not current_branch:
        break
    for key in current_branch:
        print(f">[{key}]")
    while True:
        user_input = input("Enter your selection: ")
        if user_input in current_branch:
            break
    current_branch = current_branch[user_input]

示例 Output:

Do you have a cat (0) or a dog (1)?
>[0]
>[1]
Enter your selection: asdf
Enter your selection: 3
Enter your selection: 2
Enter your selection: 1
Is your dog male (0) or female (1)?
>[0]
>[1]
Enter your selection: abcd
Enter your selection: a
Enter your selection: 0a
Enter your selection: 0
You have a male dog!
>>> 

我建議您提出一個問題,詢問 class,您可以在其中處理每個問題的行為,並簡化流程:

from dataclasses import dataclass


@dataclass
class Question:
    question: str
    answer: int = None

    def _validate(self, answer):
        if answer not in (0, 1):
            print("Please answer the following question with [0 being no] and [1 being yes]\n")
            raise ValueError

    def ask(self) -> int:
        self.answer = input(self.question)
        try:
            self.answer = int(self.answer)
            self._validate(self.answer)
        except ValueError:
            return self.ask()
        return self.answer


q1 = Question('Are you blue?')
q2 = Question('Do you like oceans?')
q3 = Question('Are you virtual?')

if q1.ask():
    if q2.ask():
        print('You are a dolphin')
    else:
        print('I don\'t know what you are')
else:
    if q3.ask():
        print('Get connected')
    else:
        print('I can\' help you')

# Also can access previous answers:
# q1.answer -> 0 or 1

暫無
暫無

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

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