Error when entering letter/character instead of number/integer - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Error when entering letter/character instead of number/integer (/thread-19297.html) |
Error when entering letter/character instead of number/integer - helplessnoobb - Jun-22-2019 Hello all, Excuse my complete lack of knowledge and "newbie-ness" as it has only been a few hours since I started my already rocky road to understanding Python. I am going through some beginner's tutorials available on web and came up with "identification"-type of codes below: The "ID number" or "idn" has to be a number between 0 and 10. print("What is your ID number, " + str(name) + "?", end=" ") idn=input() while True: if int(idn) > 10 or int(idn) < 0: print(" ERROR: the ID number is a number between 0 to 10.", end=" ") idn=input() continue else: print("Thank you, no. " + str(idn)) input() breakThe code seemed to be working fine, but when I just got curious and entered a character/alphabet/word instead of a number, it gave me an error message. I'd like to show "ERROR: ID is a number, not a character," if a character/word is entered. Here is my try, but it has been unsuccessful so far. print("What is your ID number, " + str(name) + "?", end=" ") idn=input() while True: if int(idn) > 10 or int(idn) < 0: print(" ERROR: the ID number is a number between 0 to 10.", end=" ") idn=input() continue if idn=str: print(" ERROR: ID is a number, not a character,", end=" ") idn=input() continue else: print("Thank you, no. " + str(idn)) input() breakThat "if idn=str:" is what I am struggling with. How can I set up that if-command? Thank you for your time! I'd really appreciate any advice! RE: Error when entering letter/character instead of number/integer - Gribouillis - Jun-22-2019 helplessnoobb Wrote:it gave me an error message.This is what you need to concentrate on. Python's error messages usually contain critical information about how to solve the issue. After idn = input() , the value of idn is necessarily of type str which you can check with print(isinstance(idn, str)) , which should print True. The best thing to do here is to convert to int and print an error if it is not possiblewhile True idn = input("What is your ID number? ") try: n = int(idn): except ValueError: print("Please enter a number, not", repr(idn)) continue if n in range(11): print('Thank you, your ID number is ', n) break else: print('Bad value, try again') continue RE: Error when entering letter/character instead of number/integer - ThomasL - Jun-22-2019 You have to check directly after idn=input() what you get back so what is idn. Your "if idn=str:" is complete nonsense, you really should work through a Python tutorial. |