python logic
Rhodri James
rhodri at kynesim.co.uk
Fri Sep 1 10:07:51 EDT 2017
On 01/09/17 14:30, 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)?
You don't say, but you must be running Python 2.x. If you fire up an
interactive session:
rhodri at sto-helit ~ $ python
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> help(input)
Help on built-in function input in module __builtin__:
input(...)
input([prompt]) -> value
Equivalent to eval(raw_input(prompt)).
>>>
Now raw_input() just returns the string that you typed in:
>>> raw_input("Type a number:")
Type a number:3
'3'
Notice that this is a string, in quotes, not an integer. What happens
when we eval() that?
>>> eval('3')
3
This is the integer that you wanted. Great. Now how about that letter
you typed instead?
>>> raw_input("Type a number:")
Type a number:r
'r'
>>> eval('r')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'r' is not defined
In other words, eval() looks for something named "r" but can't find
anything, so it can't evaluate the input string. You can prove this by
creating something named "r" and trying again:
>>> r = 13
>>> eval('r')
13
Going back to your question, what you want to do is to use the function
raw_input() and compare the input to the strings "1" and "2" (because
that input is a string, remember?). You could use the function int() to
convert the string to an integer, but then you would have to catch the
cases when the user types something that isn't an integer for yourself!
In Python3, it was generally agreed that the fancy behaviour of input()
caused more confusion than it was worth. input() in Python3 behaves
like raw_input() in Python2, just returning the characters typed in as a
string.
--
Rhodri James *-* Kynesim Ltd
More information about the Python-list
mailing list