0

I'm trying to create a small code that asks a user to enter a number between 1 and 100. However my Else statement will not output when entering a string. I want my Else statement to print a message if the user enters an input other than an integer or float. Here is my code.

def between():
    print ("Please enter a number between 1 and 100.")
    number = eval(input())
    if number >= 1 and number <= 100:
        print ("Thank you! You entered",number,"which is within the 1 and 100 range.")
        between()
    elif number > 100 or number < 1: 
        print ("OOPS! You entered",number,"Please enter a number between 1 and 100.")
        between()
    else: 
        print ("ERROR! You have entered an invalid value. Please try again using numerical values only.")
        between()

between()
Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
Zach
  • 11
  • Check out this thread: https://stackoverflow.com/questions/5424716/how-to-check-if-string-input-is-a-number – Nathan Mar 03 '18 at 18:50

5 Answers5

1

The easiest method would be to use try and except

num = input()
try:
    number = float(num)
    # code to do if num is a number
except ValueError:
    print("Not a number!")
    # code to do if num isn't a number

If num isn't a number, then converting it to a float would raise ValueError going on to the except. If num is a number, the coversion of it to a float would run fine, and continue on in the try.

Side note: I highly suggest not using eval(input()) but rather just input(), see this for why you shouldn't use eval. Also eval(input()) won't work with my example above.

wedg
  • 11
  • 3
  • The easiest way is not the try, that is like using brute force, there are built-in methods to check whether an object is of a class or another (In python everything is a object even the functions) – Shailyn Ortiz Mar 03 '18 at 19:04
  • @ShadyCake I used eval because it could automatically detect whether the input was an int or a float. I wanted to make the code universal to both. – Zach Mar 03 '18 at 19:06
  • @ShailynOrtiz input will always return a string, what I am doing is checking if the string can be converted into an integer. Not checking if the variable itself is an integer. – wedg Mar 03 '18 at 19:10
  • @Zach Using float() to convert it will have the same effect you are looking for, but without the dangers of eval() – wedg Mar 03 '18 at 19:10
  • In that case make use of isdigit() ;) try is not necessary at all. Not trying to promote myself tho. @ShadyCake look at my answer: https://stackoverflow.com/a/49088022/7579116 – Shailyn Ortiz Mar 03 '18 at 19:50
  • @ShailynOrtiz The only problem with isdigit() is that is doesn't work for floats, and Zach has said that they wants it to work for floats also. – wedg Mar 03 '18 at 20:23
  • @ShadyCake You are right, the only way it would work, will be something like num.replace('.','').isdigit(). – Shailyn Ortiz Mar 03 '18 at 20:36
  • @ShailynOrtiz That is a good workaround, I'd suggest mentioning that in your answer. – wedg Mar 03 '18 at 20:38
  • Updated. Good discussion tho. – Shailyn Ortiz Mar 03 '18 at 20:39
  • @ShailynOrtiz Yeah it was, but I think you meant to put .replace(',', '') instead of .replace('.', '') in your answer. Also I realised that this wouldnt work if you put in a string with multiple dots, eg 1.2.3. – wedg Mar 03 '18 at 22:52
  • oh It will work, as replace doesn't stop in the first match. it's global replacement – Shailyn Ortiz Mar 03 '18 at 22:59
  • @ShailynOrtiz No, I mean that 1.2.3, with dots removed, will return true for isdigit(), even when 1.2.3 can't be converted to a float. So the script would raise a ValueError – wedg Mar 03 '18 at 23:02
  • Now I get watch you said, so it might end up getting more complex. – Shailyn Ortiz Mar 03 '18 at 23:03
0

Try this:

print "Please enter a number between 1 and 100"
in = input()


try:
    num = int(in)

    if 1 <= num <= 100:
        print("Valid")
    else:
        print("Out of bounds")

except:

    print("Invalid")
Adi219
  • 4,712
  • 2
  • 20
  • 43
0

Try:

def between():
    print ("Please enter a number between 1 and 100.")
    number=0
    try:
        number = int(input())
    except:
        print ("ERROR! You have entered an invalid value. Please try again using numerical values only.")
        exit(1)
    if number >= 1 and number <= 100:
        print ("Thank you! You entered",number,"which is within the 1 and 100 range.")
        between()
    else: 
        print ("OOPS! You entered",number,"Please enter a number between 1 and 100.")
        between()


 between()

Note: why you use eval and input together? I don't think that's right, correct me if I'm wrong

Gustavo Topete
  • 1,246
  • 1
  • 9
  • 15
0

Try is too slow and should be avoided when not necessary

num = input("Please enter a number between 1 and 100: ")

if num.replace('.','').isdigit():
    num = float(num)
    if number >= 1 and number <= 100:
        print ("Thank you! You entered",number,"which is within the 1 and 100 range.")
        between()
    else:
        print ("OOPS! You entered",number,"Please enter a number between 1 and 100.")
        between()
else:
    print('thats not a number!')
Shailyn Ortiz
  • 766
  • 4
  • 14
0

There are a few logical issues with your code. First before using eval() you must be aware of the security risk associated with it. Consider going through this post for some insight. If you entered some arbitrary input in eval, it will most likely be a run time error.

Now, assuming that the variable actually has a value. To check if it is an integer or a float and is in the desired range or something else (possibly a string), you can not directly apply comparison operators with it because if the variable is not a number it will most likely give a TypeError during comparison with other integers.

Hence a correct approach would be to first check if the variable is of desired type by checking if type(r) is int or type(r) is float only then you should apply test for range. If the above type checking is false then you should print your "else" error message.

penguin2048
  • 1,303
  • 13
  • 25