String comparison
Paul Boddie
paul at boddie.net
Thu Oct 25 06:52:26 EDT 2001
SNeelakantan_C at zaplet.com (Shankar) wrote in message news:<4a0341c8.0110242221.592e603e at posting.google.com>...
> I started learning python recently and the examples given on
> python.org only talk about number comparison.
> I tried:
> x = input("Proceed?");
>
> if x == 'y':
> print "You typed y\n";
>
>
> This gives out a syntax error.
Firstly, drop the trailing semicolons - you don't need them in Python.
In fact, semicolons are only ever used to separate statements if
you're putting many statements on a single line. However, there does
seem to be a restriction on having an "if" statement as the last
statement on a line containing many statements:
Python 2.0.1 (#18, Jun 22 2001, 02:26:03) [MSC 32 bit (Intel)] on
win32
Type "copyright", "credits" or "license" for more information.
>>> x = 1; if x == 2:
File "<stdin>", line 1
x = 1; if x == 2:
^
SyntaxError: invalid syntax
>>>
Having said that, it could make code pretty hard to read if such
tricks were allowed.
Next, don't use "input" - use "raw_input". Otherwise, Python will
think that you want it to evaluate your input as an expression, and I
suspect that this is not what you want.
>>> x = input("Proceed?")
Proceed?y
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 0, in ?
NameError: There is no variable named 'y'
Another thing: the "print" keyword automatically writes a "\n"
character, so you might not need to include one in your string. You
might actually want this, though, but I thought that it should at
least be mentioned.
Finally, your string comparison is absolutely what you should be
using. So, that was the least of your worries. :-)
Paul
More information about the Python-list
mailing list