1

I keep hitting the else: portion of if statement any integer or string I enter goes to else:

def isThisAnInteger(isInt):
    if isinstance(isInt, int):
        #return isInt
        print("Top of If: statement")
        print(isinstance(isInt, int))
    else:        
        #print("Please enter a valid number.")
        print("Bottom of else: statement")
        print(isinstance(isInt, int))

iStart = isThisAnInteger(input("Enter the start of the range: "))
iEnd = isThisAnInteger(input("Enter the end of the range: "))

I am expecting an integer to hit the first condition, while a string or float will fall to the else condition

jps
  • 20,041
  • 15
  • 75
  • 79
BigDog169
  • 51
  • 4
  • 5
    `input()` always returns a string. This might also help: https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers – JonSG Mar 17 '23 at 20:33
  • How are you checking for type in your function? If you're checking for `type` you can use the `type()`. – Marcelo Paco Mar 17 '23 at 20:36
  • 2
    @MarceloPaco `isinstance` is the type-check that he is using. It allows you to check for classes that inherit from a certain (or multiple) classes. – Hampus Larsson Mar 17 '23 at 20:48
  • 2
    @HampusLarsson my dyslexia kicked in. I thought they were recursively calling `isThisAnInteger`. Thanks for for clarifying. – Marcelo Paco Mar 17 '23 at 20:49

1 Answers1

0
def isThisAnInteger(isInt: str):
    if isInt.isdigit():
        return int(isInt)
    else:
        print("Please enter a valid number.")

iStart = isThisAnInteger(input("Enter the start of the range: "))
iEnd = isThisAnInteger(input("Enter the end of the range: "))

Tourelou
  • 123
  • 4
  • Thanks Tourelou, That almost works, but when I put in a string like "b" it does not fall through to second condition (else:) This was the message I got... in isThisAnInteger return int(isInt) ValueError: invalid literal for int() with base 10: 'b' – BigDog169 Mar 17 '23 at 22:06
  • Sorry BigDog169, I forgot to put «()» after the «isdigit» call. It sould be read : `if isInt.isdigit():` – Tourelou Mar 18 '23 at 15:26
  • Thank you, that worked. Shouldnt the code blow up without the parens()? – BigDog169 Mar 19 '23 at 03:07