I am trying to modify a program that plays the game 'Rock, Paper, Scissors', so that it observes data validation. This objective here is that the validation is done so by ensuring that the user input is equal to 'rock', 'paper' or 'scissors', before userMove will return
Below is a function, I created for the user's input where I have used a while not in to validate the user's input and either return a valid input or print a string, asking for a valid input.
Question: is this the most effective way to validate in this instance? Perhaps using the ValueError function is more effective?
def userMove():
usersMove = input("Time to make your choice: ")
while usersMove not in ['rock', 'paper', 'scissors']:
print("That is not a valid")
usersMove = input("Time to make your choice: ")
return usersMove
One thing you could do is use a set since lookups are faster in sets than in list, also as a comment said, using .lower() would make your code more robust:
def userMove():
usersMove = input("Time to make your choice: ")
while usersMove.lower() not in {'rock', 'paper', 'scissors'}:
print("That is not a valid")
usersMove = input("Time to make your choice: ")
return usersMove
EDIT
Also, as @utengr pointed out, using my previous recommendations you could transform your code like this also,
def userMove():
while True:
usersMove = input("Time to make your choice: ")
if usersMove.lower() in {'rock', 'paper', 'scissors'}:
return usersMove
print("That is not a valid")
Note that your question was about performance. Using the second solution will not affect performance in any way, the main gain here is regarding readability since you compact the code into one block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With