Ted Mosby
Ted Mosby

Reputation: 1456

Try except with If statements in Python

If I'm trying to prompt a user for their street name and they enter a # symbol i want to return an error and loop back to the top until they have entered a valid name.

Code:

def streetname():
    while True:
        try:
            nameinput = str(input("Please enter a street name: "))
        except Exception: # want to print error == if nameinput.find('#') > -1:
           print("Error: name contains #, please try again")
           continue 
        break
    return nameinput

Goal of code: I want to prompt user for street name until they enter a valid name. If it contains '#', print error and try again. if it's valid, return nameinput.

I'm not quite sure how to use try and except with if statements

Upvotes: 0

Views: 384

Answers (2)

reticentroot
reticentroot

Reputation: 3682

First off, you're using a python's general Exception class. A string with a pound sign in it wouldn't trigger any of python's native exceptions, you have to write your own exception class and then call it.. or you can do something like this

if '#' in nameinput: #pound sign was found in the string
  #either raise an Exception
  raise('Can not use pound sign') # though this will probably break the while loop
  # or
  print 'can not use pound sign'
  continue # to go back to the top of the while loop and prompt the user again

Upvotes: 1

AliciaBytes
AliciaBytes

Reputation: 7429

You probably shouldn't use try...except for such a simple input check, that can easily done with if alone.

def streetname():
    while True:
        nameinput = input("Please enter a street name: ")

        if "#" in nameinput:
            print("Error: name contains #, please try again")
            continue

        return nameinput

If you find a '#' in the string simply restart the loop, otherwise just return the name out of the function.

Also input already returns a str in Python 3, so there's no need to convert it. In Python 2 you should use raw_input instead which will also return a str.

Upvotes: 2

Related Questions