Reputation: 121
So I'm trying to get this function to return what I write only if it is equal to a character in an array. If not I want it to keep looping.
def pick():
picks = input('Type one letter. ')
choice = {'q', 'w', 'e', 'r', 't', 'y'}
for x in choice:
while x in choice != picks:
picks = input('Pick again. ')
else:
return x
pick()
I am just getting really confused with this.
Example:
Type one letter. z
Pick again. q
then it will return q
to the function to be used in another function.
Also It has to only continue to the next function if this one is right (returns the proper character). The other function while compare this functions answer to its own. Will it stop other functions from "starting" while this one keeps looping if it is not right?
Upvotes: 2
Views: 320
Reputation: 24739
Try (Python 3):
def pick():
choices = {'q', 'w', 'e', 'r', 't', 'y'}
picked = input('Type one letter: ')
while picked not in choices:
picked = input('Pick again: ')
return picked
pick()
For Python 2:
def pick():
choices = {'q', 'w', 'e', 'r', 't', 'y'}
picked = raw_input('Type one letter: ')
while picked not in choices:
picked = raw_input('Pick again: ')
return picked
pick()
You don't need to iterate through choices
every time as in
checks against every member of the set
.
When you use input()
in Python 2, Python will try to interpret the input as a variable, but raw_input()
will return a string.
And, yes, this function will block until valid input is received, stopping subsequent functions from executing.
Upvotes: 1
Reputation: 65460
It is unnecessary to loop through choices every time. Also I'm not quite sure what you're trying to do with your while
condition, but something like this should do the trick. The motif x in y
returns a boolean which indicates if x
is a member of y
.
def pick():
picks = input('Type one letter. ')
choice = {'q', 'w', 'e', 'r', 't', 'y'}
while picks not in choice:
picks = input('Pick again. ')
return picks
pick()
Also I would probably do a little bit to cleanup the user's input.
while picks.lower().rstrip() not in choice:
Upvotes: 3