I am somewhat new to python and have a very basic understanding.
I am creating a very simple program that works as a decision map. The user types 0 for no, and 1 for yes, in order to continue down the decision map and ultimately reach a conclusion. For each decision, the answer (0 or 1) is saved in a new variable.
MY PROBLEM: I created a function to validate that the user is entering a valid response. I want to use this function after every-time I ask for a new response for each new decision/ variable. For example, in the first variable, seq , if the user enters 2, it should enter the validation function and enter a loop until the user enters 0 or 1. However, once they enter 0 or 1, I don't know how to re-assign that new value to seq in order to continue with the decision map.
What I have tried: Setting x to global, initiate x = 0
, set the variable (ie seq ) to global, and add seq = valid_user_input(x)
Any help would be greatly appreciated. I am looking for a simple solution that is hopefully not too advanced for me. HERE IS A LINK TO EDIT MY CODE! Repl.it map program
#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
You design your function so it has one task: return 0 or 1 to a given text
(your question):
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)
and only ever leave the function if the input is valid:
Outputs for inputs: 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
More on validation:
Here's a contrived example. I'm not even suggesting that this is a good way of doing what you're trying to achieve (deleting the prompt
key-value pair feels lame) - All I'm trying to show here is that a data-driven approach might be desirable since it helps to cut down on if-statements.
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]
Example 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!
>>>
I would recommend you making a question asking class, where you can handle the behaviour for every question, and have your flow simplified:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.