3

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)

Mark
  • 90,562
  • 7
  • 108
  • 148
awoldt
  • 379
  • 1
  • 4
  • 10
  • 3
    Try `if userGuess.isnumeric():` - see [`str.isnumeric()`](https://docs.python.org/3.8/library/stdtypes.html#str.isnumeric). – metatoaster Jun 09 '20 at 03:57
  • 1
    What about numbers > 9? – Aivar Paalberg Jun 09 '20 at 03:59
  • 1
    Is `userGuess` limited to a single character? – tdelaney Jun 09 '20 at 04:02
  • As a note on examples, `continue` can't be used outside of a loop. Its best to post a running example. In your case, assigning a value to `userGuess` and leaving out the `continue`. – tdelaney Jun 09 '20 at 04:07
  • thanks for all the help. i didn't know you can int() with a str that's a number – awoldt Jun 09 '20 at 04:11
  • If `userGuess` is any string of digits greater than 0 length, then `int` works. Suppose its `User1234`, `int` would fail, but the guess would contain digits. I don't know what you want in that case. – tdelaney Jun 09 '20 at 04:15

3 Answers3

3
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
chumbaloo
  • 671
  • 6
  • 16
  • could you explain how the loop if userGuess in possibilities: works? – awoldt Jun 09 '20 at 04:25
  • Sure, no problems. The if statement is followed by a conditional check (which if evaluated to true, executes the next indented block of code). The use of the keyword in, is best explained already by this answer (https://stackoverflow.com/a/38204487). It simply checks if the value of userGuess is inside the list of items in possibilities. – chumbaloo Jun 09 '20 at 04:29
3

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")
chumbaloo
  • 671
  • 6
  • 16
bhristov
  • 3,137
  • 2
  • 10
  • 26
0

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.

tdelaney
  • 73,364
  • 6
  • 83
  • 116