Reputation: 848
I have a tuple of values as follows:
commands = ("time", "weather", "note")
I get an input from the user and I check if the input matches any value in the tuple as follows:
if user_input.startswith(commands):
# Do stuff based on the command
What I would like to do is exactly as the above, but with the matched item returned. I tried many methods, but nothing really worked. Thank you in advance.
Edit: At some point I thought I could use the Walrus operator, but you would figure out it wouldn't work.
if user_input.startswith(returned_command := commands):
command = returned_command
# actually command only gets the commands variable.
Upvotes: 0
Views: 565
Reputation: 3185
With Python 3.8 or later this should work:
if any(user_input.startswith(returned_command := c) for c in commands):
print(returned_command)
Upvotes: 0
Reputation: 4649
You can use any
.
user_input = input()
if any(user_input.startswith(s) for s in commands):
# The input is valid.
If you want to ask for user inputs until their reply is valid, shove that in a while loop.
match = None
while True:
user_input = input()
if any(user_input.startswith(s) for s in commands): # Make sure there is a match at all.
for c in commands:
if user_input.startswith(c):
match = c # Find which command matched in particular.
break # Exit the loop.
else:
print(f"Your selection should be one of {commands}.")
# ...
# Do something with the now valid input and matched element.
# ...
Upvotes: 0
Reputation: 61032
This function takes a function of one argument and a list of arguments, and will return the first argument that makes the function return a truthy value. Otherwise, it will raise an error:
def first_matching(matches, candidates):
try:
return next(filter(matches, candidates))
except StopIteration:
raise ValueError("No matching candidate")
result = first_matching(user_input.startswith, commands)
Upvotes: 1
Reputation: 610
Try this. You can store your functions inside a dictionary and call them.
def print_time():
print("Time")
def exit_now():
exit()
def print_something(*args):
for item in args:
print(item)
command_dict = {
"time": print_time,
"something": print_something,
"exit": exit_now
}
while True:
user_input = input("Input command: ")
command, *args = user_input.split()
command_dict[command](*args)
output:
Input command: time
Time
Input command: something 1 2 3
1
2
3
Input command: exit
Upvotes: 1