Check out the following simple code:

#!/bin/python

print "1 - echo 1"
print "2 - echo 2"

answer = input("Enter your choice - ")

if answer == 1:
  print "1"
elif answer == 2:
  print "2"
else:
  print "Invalid choice!"


The else statement noted above works fine for numeric values other then 1 or 2. 
 But if a user types in alphanumeric data (letters) into this, it blows up.  
Check out the following:

[root@ansi ~]$ ./trash
1 - echo 1
2 - echo 2
Enter your choice - 3
Invalid choice!

[root@ansi ~]$ ./trash
1 - echo 1
2 - echo 2
Enter your choice - r
Traceback (most recent call last):
  File "./trash", line 6, in <module>
    answer = input("Enter your choice - ")
  File "<string>", line 1, in <module>
NameError: name 'r' is not defined

I would expect the same behavior from both runs.  Why does Python differ in the 
way it treats a character in that program?  Finally, how to accomodate for such 
(how to fix)?

TIA
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to