Era el Fri, 1 Sep 2017 06:30:43 -0700 (PDT) en comp.lang.python, cuando de repente SS dijo lo siguiente acerca de python logic:
> 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 In Python 2, the input() function evaluates whatever you enter in the prompt. In your case, Python is trying to evaluate 'r' as if it was a variable or something. Use the raw_input() function instead. However, note that if you ever want to run your script with Python 3 you'll have to switch back to using input(), which does exactly the same as Python 2's raw_input(). -- https://mail.python.org/mailman/listinfo/python-list