1

I am working my way through Python for Everyone and I am stuck at this junction. To my eye I have stated that the ValueError is only to be raised if 'num' is anything other than a integer. However when I run the code the error is raised everytime regardless of input. Can anyone nudge me in the right direction?

Extensively googled but I'm not entirely too sure what specifically I should google for...

largest = None
smallest = None
while True:
    try:
        num = input("Enter a number: ")
        if num != int : raise ValueError
        elif num == "done" : break
    except ValueError:
        print("Error. Please enter an integer or type 'done' to run the program.")
        quit()


print("Maximum", largest)
print("Minimum", smallest)

The code always raises ValueError even when the input is an integer.

anky
  • 74,114
  • 11
  • 41
  • 70
  • 1
    `input()` always returns a string – anky Jun 08 '19 at 15:15
  • It is probably a string. – Jeppe Jun 08 '19 at 15:15
  • 1
    Even if it were an integer, it would still be different from the *type* `int`. – mkrieger1 Jun 08 '19 at 15:16
  • You probably meant `if not isinstance(num, int)`, but that will *also* always be true, because `input` always returns a string. – chepner Jun 08 '19 at 15:16
  • `num != int` is an equality comparison, not a type check. – Code-Apprentice Jun 08 '19 at 15:20
  • nice first post - congrats. Finding duplicates of your questions is an art-form - I would always go to google and use something like `how to convert input to int python` to find duplicates on SO that help you fix your code by comparing what you came up with to answers to said google question results. – Patrick Artner Jun 08 '19 at 15:24

2 Answers2

2

This line checks if the inputted string is literally equal to the builtin type int:

if num != int : raise ValueError

 

Other problem is that the input() function always returns a string. So if you want to raise a ValueError when the user inputs anything but a number, simply do:

inputted = input("Enter a number: ")
num = int(inputted)  # raises ValueError when cannot be converted to int
ruohola
  • 21,987
  • 6
  • 62
  • 97
2

If you want to check if the string entered can be converted into an int, just try it:

while True:
    num = input("Enter a number: ")
    if num == "done":
        break
    try:
        num = int(num)
    except ValueError:
        continue
chepner
  • 497,756
  • 71
  • 530
  • 681