python logic
SS
sami.strat at gmail.com
Fri Sep 1 12:55:53 EDT 2017
On Friday, September 1, 2017 at 9:32:16 AM UTC-4, SS wrote:
> 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 at ansi ~]$ ./trash
> 1 - echo 1
> 2 - echo 2
> Enter your choice - 3
> Invalid choice!
>
> [root at 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
raw_input, nice. Thanks!!
More information about the Python-list
mailing list