I try to check input using:
try:
x = str(input("enter a string? "))
except:
print(“Invalid.”)
I enter a number at the prompt and it works. How do I detect the wrong input?
I try to check input using:
try:
x = str(input("enter a string? "))
except:
print(“Invalid.”)
I enter a number at the prompt and it works. How do I detect the wrong input?
Hi.
First off, you don’t need x = str(input("enter a string? "))
because the input()
function will return a string by default, so: x = input("enter a string? ")
Maybe something like this, if you want to find out if any of the characters is not ‘alpha’ or a space?
x = input("enter a string? ")
for char in x:
if char.isalpha() or char == ' ':
pass
else:
print("Error in input")
break
You need to better define what your input will and will not accept as ‘valid’ or ‘invalid’.
Note: any character that is not ‘a’ to ‘z’ or ‘A’ to ‘Z’ will fail the above test.
edit to add:
Maybe a better way would be to use this, to filter just for numbers:
for char in x:
if char.isdigit():
print("Error in input")
break
Why is a string made up of digits “wrong input”? It is still a string of characters.
There is no point in calling str()
on the result of input()
, because input()
already returns a string. So that’s just a waste of time which does nothing.
Nothing inside the try
block can fail, so the except
clause will never run. Which is good, because …
This sort of try...except
block is one of the most diabolically awful things you can write, trust me, do not get into the habit of doing this!
# This is bad, don't do it!
try:
code
except:
print("Invalid")
The Python interpreter makes a huge effort to give the programmer a lot of information about the error, and why it happened, and you replace that with just “Invalid”. That’s terrible! As a programmer, there are very few things worse than such pointless and uninformative error messages as “Invalid” and “An error occurred”.
If you are only looking to reject numeric characters (digits) you can write this:
if any(c.isdigit() for c in x):
print("Found a digit")