input check help! - 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: input check help! (/thread-27311.html) |
input check help! - bntayfur - Jun-02-2020 Hello, i am new to Python so i couldn't figure out how to check the input. I want to get an input from the user(integer or float) and want to give an error message when it enters anything else(letter or any special character). So far i know this works for the integer: while True : try: x = int(input('please enter an integer: ')) print(x) break except ValueError: print('not valid')First can someone please explain the logic of this. I didn't understand it thoroughly. But if i want it to accept decimal numbers as well integers what should i write? (very basically cause i am new) Here are some of the things i tried which none of them worked. 1) radius= input("enter a number: ") if isinstance(radius,float): print(radius) elif isinstance (radius,int): print(radius) else: print("Not a number")2) radius= input("enter number: ") if isinstance(radius,numbers.Real): print(radius) else: print("not number")3) radius= input("enter number: ") if type(radius) in (float,int): print(radius) else: print("not a number")4) x=input('please enter integer: ') if type(x) is int: print(x) elif type(x) is float: print(x) else: print('error')5) x=input('please enter integer: ') if not type(x) is int: raise TypeError('only numbers allowed') RE: input check help! - bowlofred - Jun-02-2020 Instead of x=int(...) (which tries to interpret the input string as an integer), you could just do x=float(...) . That will accept integers as well as floating-point numbers.
RE: input check help! - bntayfur - Jun-02-2020 Thanks! for the first one it works, but what is wrong with the others? RE: input check help! - bowlofred - Jun-02-2020 Whenever you input something like x = input()Then the variable ( x in this case) is always a string. In some of your other examples you're asking if it's a float, or an instance of a float, etc. It will never be. The contents might look like an integer, but the variable remains a string. You can attempt to cast that value it to a int or something else:x = input() i = int(x)But of course that can fail if the input text has characters in it. What your first one does is try to cast it this way, and print a message if that fails.x = input() try: i = int(x) [do stuff here with your int...] except ValueError: # Ooops, something in the try section failed with a valueerror. That likely # means the string didn't look like an int. We can complain here, and maybe # loop to retry. print(f"The input {x} doesn't seem to be a number. I don't know what to do with it.") |