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.

How can I check to make sure a string is entered?

This is my function:

def checkInput(prompt):
  result = None
  while result == None:
    try:
      result = input(prompt)
      return result
    except:
      print("Please insert an appropriate value!")

Recommended Answers

All 10 Replies

In python 3, after result = input(prompt) , result is a string in the python sense (an instance of the datatype 'str'). Examples of strings are

"" # the empty string
"    " # a string of white space
"3.14159" # a string with the representation of a number
"hello world  " # another string, with white space at the end

result.strip() is the string with white space removed at both ends, so if there was nothing significant in the user's input, it's the empty string, so:

if not result.strip():
  ... # the input was empty, do something

Also notice that even the empty string is not None, so be careful about your loop condition

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

found=False
for ltr in input_string.strip():
    if "a" <= ltr.lower() <= "z":
        found=True
if found...etc 
#
# list comprehension
x = [ltr for ltr in variable if "a" <= ltr.lower() <= "z"]
if len(x)

That does work, but two things.

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.

That has to do with the flow of control (logic) of the program as a whole: Something you did not show us.

Alright, here is a snippet from my script.

def checkInput(prompt):
  result = input(prompt)
  if not result.strip():
    print("Please enter an appropriate value!")
  return result

def convert():
  loop = 1
  while loop == 1:
    deg = checkInput("\nDo you have Celsius, Fahrenheit, or Kelvin? ")

    # Celsius calculations
    if deg == 'c' or deg == 'celsius' or deg == 'Celsius':
      cdeg = checkInput("Convert to: Fahrenheit or Kelvin? ")
      if cdeg == 'f' or cdeg == 'fahrenheit' or cdeg == 'Fahrenheit':
        fcel = getFloat("\nWhat is the degrees in Celsius? ")
        print ("\n{} degrees Celsius is {} degrees Fahrenheit.\n".format(fcel, fcel * 1.8 + 32))
      if cdeg == 'k' or cdeg == 'kelvin' or cdeg == 'Kelvin':
        kcel = getFloat("\nWhat is the degrees in Celsius? ")
        print("\n{} degrees Celsius is {} degrees Kelvin.\n".format(kcel, kcel + 273))

Alright, here is a snippet from my script.

def checkInput(prompt):
  result = input(prompt)
  if not result.strip():
    print("Please enter an appropriate value!")
  return result

def convert():
  loop = 1
  while loop == 1:
    deg = checkInput("\nDo you have Celsius, Fahrenheit, or Kelvin? ")

    # Celsius calculations
    if deg == 'c' or deg == 'celsius' or deg == 'Celsius':
      cdeg = checkInput("Convert to: Fahrenheit or Kelvin? ")
      if cdeg == 'f' or cdeg == 'fahrenheit' or cdeg == 'Fahrenheit':
        fcel = getFloat("\nWhat is the degrees in Celsius? ")
        print ("\n{} degrees Celsius is {} degrees Fahrenheit.\n".format(fcel, fcel * 1.8 + 32))
      if cdeg == 'k' or cdeg == 'kelvin' or cdeg == 'Kelvin':
        kcel = getFloat("\nWhat is the degrees in Celsius? ")
        print("\n{} degrees Celsius is {} degrees Kelvin.\n".format(kcel, kcel + 273))

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

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.

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 --> " + ", ".join(values_list))


deg = checkInput("Do you have Celsius, Fahrenheit, or Kelvin? ", \
                ['c', 'celsius', 'f', 'fahrenheit', 'k', 'kelvin'])
cdeg = checkInput("Convert to: Fahrenheit or Kelvin? ", \
                 ['f', 'fahrenheit', 'k', 'kelvin'])
print deg, cdeg


def getFloat(prompt):
    while True:
        result = input(prompt)
        try:
            return float(result)
        except:
            print("Enter a number only\n")

fcel = getFloat("What is the degrees in Celsius? ")
print fcel
commented: Good code (except not functions first) +13

Thank you all so much. It works flawlessly now.

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.

Woooee, your function is what works flawlessly. Thank you for your help.

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.

I agree, but we're only supposed to help you write your code, not to do all the work for you :)

I agree, but we're only supposed to help you write your code, not to do all the work for you :)

Ah, touché, touché. :P. Well, at least now I understand how it works!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.