An Intro to
Programming
with Python

Fall 2006
course
navigation

Wed Sep 13

chapter 2

>>> a = 1,2,3 (1, 2, 3) # This is a "tuple" with 3 parts >>> a * 2 # Do these do anything? >>> a + 2 # If so, what? >>> a**2 >>> a = 10 >>> b = 20 >>> a,b = b,a # swap the values in 'a' and 'b' for <var> in <sequence>: <body>
Here's an example
for odd in [1,3,5,7,9]: print odd*odd
Here's another way to make a sequence :
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Jim's aside: print

Python's "print" is a bit funky, IMHO
Language X :
print("hi there")
Usually I expect either always parens, or optional parens
a = sqrt 2
But at first glimpse, Python seems to allow either.
>>> print "hi there" hi there >>> print("hi there") hi there
Until you look closer.
>>> a=10 >>> print "a is", 10 a is 10 print("a is",10) ('a is', 10)
Oops - what was that?
It turns out that "print" in Python isn't a function, like sqrt(); all Python's functions require parens. Instead, "print" in python is a built-in language primitive, like "if". And it never takes parens.
What? But we saw it work with parens! Remember,
>>> print("hi there") hi there
Ah. Well, what you thought you saw was this:
>>> x = ("hi there") >>> print x hi there
Where the parens are used to group things together. In this case, there just happens to be one thing.
The place you can really see this happen is with Python "tuples", which are groups of things clumped together. Like this :
>>> point = 10,20 >>> point (10, 20)
Ah hah. Theere are those parens again. This is the way Python always outputs a tuple. So now we see why we have
>>> print(1,2) (1, 2)
because it's the same as
>>> point = (1,2) >>> print point (1, 2)
http://cs.marlboro.edu/ courses/ fall2006/python/ notes/ sep_13
last modified Wednesday September 13 2006 10:28 am EDT