Reputation: 419
I'm fairly new to Python. I have the following if statement:
if(userGuess == "0" or userGuess == "1" or userGuess == "2" or userGuess == "3" or userGuess == "4" or userGuess == "5" or userGuess == "6" or userGuess == "7" or userGuess == "8" or userGuess == "9"):
print("\n>>>error: cannot use integers\n")
continue
Basically, the loop will reset if the user inputs any numbers. Is there any way to write this statement to make it a little more efficient? (i.e less code and cleaner)
Upvotes: 3
Views: 73
Reputation: 77347
Assuming userGuess
is a string and can be other than a single character,
if(any(c.isdigit() for c in userGuess):
....
if the guess should be exactly one character, you can
if(len(userGuess) != 1 or userGuess in "0123456789"):
....
or
if(len(userGuess) != or userGuess.isdigit()):
...
Come to think of it, isdigit
is the better way to go. Suppose the user entered the Bengali number ৩
? ৩.isdigit()
is True
.
Upvotes: 0
Reputation: 3187
You can do this:
nums = [str(i) for i in range(10)] # gets a list of nums from 0 to 9
if userGuess in nums:
print("Num found")
Upvotes: 3
Reputation: 721
possibilities = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
if userGuess in possibilities:
#do something
Or alternatively, if you are ok with doing a comparison with integers instead you could do the following:
if userGuess < 10:
#do something
Upvotes: 3