GAVDADDY
GAVDADDY

Reputation: 21

How do I stop the program from crashing when given a letter in the place of a number?

employee = float(raw_input('Employee code number or 0 for guest:') or 0.0)

if employee == isalpha:
    print "Nice try buddy"
    print "Welcome BIG_OLD_BUDDY" 

This code does not recognize alphabetical input.

Upvotes: 0

Views: 840

Answers (4)

yt.
yt.

Reputation: 437

If you want it to only accept positive integers you can check usingisdigit() which is basically the opposite of isalpha().Try:

    employee = raw_input('Employee code number or 0 for guest:')

    if employee.isdigit()==False:
      print "Nice try buddy"
      print "Welcome BIG_OLD_BUDDY"
    elif int(employee)==0:
      print "You are a guest"
    else:
      print "Your employee no is:" ,employee

I also added a bit of code using elif to check if you're a guest

Upvotes: 0

Ujjaval Moradiya
Ujjaval Moradiya

Reputation: 222

There are 2 ways.

  1. You can catch the the exceptions and pass.
try:
    employee = float(raw_input('Employee code number or 0 for guest: ') or 0.0)
except KnownException:
    #  You can handle Known exception here.
    pass
except Exception, e:
    # notify user
    print str(e)
  1. Check for the type of input and then do what you want to do.
employee = raw_input('Employee code number or 0 for guest:')

if(employee.isalpha()):
    print "Nice try buddy"
    print "Welcome BIG_OLD_BUDDY"
else:
    print "Your employee no is:" + str(employee)

Do not use try and catch until and unless there are chances of unknown exceptions. To handle things with if and else are recommended.

Read more about : why not to use exceptions as regular flow of control

Upvotes: 1

Mohd
Mohd

Reputation: 5613

You can use try/except as the other answer suggested, and if you want to use str.isalpha() you have to call it on the string, not compare it with the string. For example:

employee = raw_input('Employee code number or 0 for guest:')

if employee.isalpha():
    print "Nice try buddy"
    print "Welcome BIG_OLD_BUDDY" 
else:
    employee = float(employee)

Upvotes: 0

SomeGuyOnAComputer
SomeGuyOnAComputer

Reputation: 6208

Use a try

try:
    employee = float(raw_input('Employee code number or 0 for guest: ') or 0.0)
except ValueError:
    print "Nice try buddy"
    print "Welcome BIG_OLD_BUDDY"

Upvotes: 0

Related Questions