Using Try, Except to catch a blank input

I'm trying to using Try, Except to check an input() to make sure it's not blank.

I'm using it at a different part of my program to check a float(input()) and it catches it if someone leaves it blank or enters a string, but I assume that's because it's checking the type to make sure it's a number, and a string isn't a number and leaving it blank isn't a number.

However, for just the input(), I need to check to make sure it's not a number and to check to make sure it isn't blank, but since it's just a plain-ol' input, it accepts anything thrown into it, so it doesn't raise an exception.

[QUOTE=;][/QUOTE]
You can pass the acceptable values to the checkInput() function and let it do the work. For the getFloat() function, use a try/except to test for correct input. [code]def checkInput(prompt, values_list):
print "\n"
while True:
result = input(prompt).strip()
if result.lower() in values_list:
return result
print("Please enter an appropriate value … Read More

[QUOTE=poker158149;1642378]Gribouillis, your function worked nicely, but it didn't stop the user from entering an incorrect value, it just stopped them from leaving it blank.[/QUOTE]
I agree, but we're only supposed to help you write your code, not to do all the work for you :) Read More

However, for just the input(), I need to check to make sure it's not a number and to check to make sure it isn't blank

To make sure it isn't blank, check that len(variable.strip()) > 0
To make sure that it is not a number, you can use not variable.isdigit(), although a number with a comma or decimal point in it is not isdigit() so you can also use

1) It doesn't check to make sure it's a string and not a number, but I'm not sure how to get around that since everything in the input is automatically made into a string without the proper conversion.

and

2) After it prints out the error to the user, it restarts the program.

For example, let's say this is the tree of my program:
-
--
---
----

If I use the "if not result.strip()" and it catches an error on an input at the --- branch, it'll print out the "Enter a value" or whatever and then send the user back to the - branch.

However, with the Try, Except that I'm using to make sure the user enters a number at branch ----, if the user doesn't enter a number and the program catches it, it keeps them at the ---- branch so they can try again.

You can add a loop, and a try block to catch all errors, since there are more than one check. When a check fails, you can 'raise ValueError' like this

def checkInput(prompt):
while True:
result = input(prompt).strip()
try:
if not result:
raise ValueError
# here add more checks and raise ValueError if any of them fails
except ValueError:
print("Please enter an appropriate value!")
else:
return result