0

Good afternoon everyone.

First of all I am a total beginer in coding and Python itself. To be honest I am not even sure is that a proper place to ask such a 'newbie' question.

But to the point.

During the online course I was asked to write a simple program to guess numbers. I did that and the code works quite ok: https://pastebin.com/XwZ2qcab

Although I wanted to improve the code to allow user to type a non int variable and not crash. I have used ' if type(userNumber) != int:' in the upgraded version of the code: https://pastebin.com/JQarjjSw but it does not work.

The issue I have is (I think) here:

for i in range(1, 7):
userNumber = input('Take a guess')
if type(userNumber) != int: #This line is my main issue, if I delete it code works like a charm.
    break
elif int(userNumber) > int(number):
    print('No! Your number is too high. Try again')
elif int(userNumber) < int(number):
    print('No! Your number is too low. Try again')
else:
    break

I have no idea why the line if type(userNumber) != int: break is not executed and pyCharm goes directly to: elif int(userNumber) > int(number): and crashes.

Funny thing is that on pythontutor.com code works as intended. Checks for userNumber and if it is not an int breakes the IF loop.

Hope that is somehow clear.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
  • 1
    Please [edit] your post and put all of your code in the body of the question itself, not as Pastebin links. External links can break over time. – MattDMo May 25 '22 at 17:34
  • 2
    The `input()` function always returns a string. Do the answers to this [question](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) help at all? – quamrana May 25 '22 at 17:37
  • Ok so if the input() always returns a string why does it pass the 'if type(userNumber) != int:'? How I see it, if the userName is string this should breturn True in this line and brake should be execued. – LuciusVerinus May 25 '22 at 17:41
  • 1
    When I try your code I always get the first `if` and `break` terminating the loop. – quamrana May 25 '22 at 17:46
  • 1
    I also cannot reproduce the issue you have of the `if` getting skipped. Rather, it *always* runs. Are you sure you're running the most recent version of your code? – Blckknght May 25 '22 at 17:47
  • It is indeed very odd. As I have mentioned it works on pythontutor but drops an error on my pyCharm. – LuciusVerinus May 25 '22 at 17:51
  • I'm running PyCharm 2022.1 and python 3.10 and I always get the first `if` taken. – quamrana May 25 '22 at 17:55
  • I found out what was the issue. I was running the old version of the code while having the newest version opened in editor (or something like that). Like I said I am new. Thank you for the help. – LuciusVerinus May 25 '22 at 19:54

3 Answers3

0

You get your userNumber variable from input function. And it always returns a string. So you have a few options you can use to check if user gives a digits.

First option is to use str.isdigit() method

userNumber = input('Take a guess')
if not userNunber.isdigit():
    # user entered something else than digits
    break

Another option could be using try-except method:

userNumber = input('Take a guess')
try:
    # try to convert user input to integer
    userNumber = int(userNumber)
except ValueError:
    # We failed so user entered invalid value
    break

ex4
  • 2,289
  • 1
  • 14
  • 21
0

In this case, you need to use a try… except… statement:

try:
    int(“12ab”)
except ValueError:
    print(“Not a number”)

Your full code would be:


for i in range(1, 7):
    userNumber = input('Take a guess')
    try:
        num = int(userNumber)
    except ValueError:
        print(“Not a number”)
        break

    if num > int(number):
        print('No! Your number is too high. Try again')
    elif num < int(number):
        print('No! Your number is too low. Try again')
    else:
        break

You can read more about it here.

ByteAtATime
  • 130
  • 1
  • 8
  • Thanks, will try that. I am curious though why the method I have used did not work? 'if type(userNumber) != int: break' seems logical but I am sure I am missing something. – LuciusVerinus May 25 '22 at 17:46
  • This is because `input()` always returns a string, but you’re checking for an `int`. You can check the documentation for [`input()` here](https://docs.python.org/3/library/functions.html#input). – ByteAtATime May 25 '22 at 17:55
0

Extending on ex4's answer, you should use .isdigit() to check if the input is numeric, however where this is a game I assume you don't just want the game to end using a break when the player enters a bad input and you'd rather have them guess again.

Try the following segment. It takes inputs until the player enters an input which isn't a digit, where it gets the player to enter another input until it is a digit.

for i in range(1, 7):
    userNumber = input('Take a guess')
    while not userNumber.isdigit():
        userNumber = input('What you have entered is not a number, please guess again')
    if int(userNumber) > int(number):
        print('No! Your number is too high. Try again')
    elif int(userNumber) < int(number):
        print('No! Your number is too low. Try again')
    else:
        break
lime
  • 801
  • 8
  • 21
  • @LuciusVerinus Glad to hear! You might want to mark the question as correct for anyone looking to reference similar questions in the future – lime May 25 '22 at 21:16