[英]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.