Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Python Lecture 1

The document summarizes an introductory lecture on Python for a CS 11 track at Caltech. It outlines prerequisites like getting a CS account and learning UNIX. It then covers Python syntax at a high level, basic data types, control flow structures, functions, modules, strings, file I/O and command line arguments. The first assignment is posted and due one week later.

Uploaded by

Peter Stephen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Python Lecture 1

The document summarizes an introductory lecture on Python for a CS 11 track at Caltech. It outlines prerequisites like getting a CS account and learning UNIX. It then covers Python syntax at a high level, basic data types, control flow structures, functions, modules, strings, file I/O and command line arguments. The first assignment is posted and due one week later.

Uploaded by

Peter Stephen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

CS 11 Python track: lecture 1

n Preliminaries
n Need a CS cluster account
n http://acctreq.cms.caltech.edu/cgi-bin/request.cgi
n Need to know UNIX
n ITS tutorial linked from track home page
n Track home page:
n courses.cms.caltech.edu/cs11/material/python
Administrative stuff
n See admin web page:
http://www.cs.caltech.edu/courses/cs11/material/
python/admin.html
n Covers how to get software set up, how
to submit labs, collaboration policy,
grading policy, etc.
Assignments
n 1st assignment is posted now

n Due one week after class, midnight


Textbook
n None required
n "Learning Python" by Mark Lutz
n Most people learn from online docs
n links on web site
Why learn Python?
n "Scripting language"
n Very easy to learn
n Interactive front-end for C/C++ code
n Object-oriented
n Powerful, scalable
n Lots of libraries
n Fun to use
Python syntax
n Much of it is similar to C syntax
n Exceptions:
n missing operators: ++, --
n no {} for blocks; uses whitespace
n different keywords
n lots of extra features
n no type declarations!
Starting and exiting Python
% python
Python 2.7.2 ...
>>> print "hello"
hello
>>> ^D
%
Simple data types
n Numbers
n integer
n floating-point
n complex!
n Strings
n characters are strings of length 1
n Booleans are 0/1 (or False/True)
Simple data types: operators
n + - * / % (like C)
n += -= etc. (no ++ or --)
n Assignment using =
but semantics are different!
n

a = 1
a = "foo" # OK
n Can also use + to concatenate strings
Compound data types (1)
n Lists:
a = [1, 2, 3, 4, 5]
print a[1] # 2
some_list = []
some_list.append("foo")
some_list.append(12)
print len(some_list) # 2
Compound data types (2)
n Dictionaries:
like an array indexed by a string
n

d = { "foo" : 1, "bar" : 2 }
print d["bar"] # 2
some_dict = {}
some_dict["foo"] = "yow!"
print some_dict.keys() # ["foo"]
Compound data types (3)
n Tuples:
a = (1, 2, 3, 4, 5)
print a[1] # 2
empty_tuple = ()
n Difference between lists and tuples:
n lists are mutable; tuples are immutable
n lists can expand, tuples can’t
n tuples are slightly faster
Compound data types (4)
n Objects:
class Thingy:
# next week’s lecture
t = Thingy()
t.method()
print t.field
n Built-in data structures (lists, dictionaries)
are also objects
n though internal representation is different
Control flow (1)
n if, if/else, if/elif/else
if a == 0:
print "zero!"
elif a < 0:
print "negative!"
else:
print "positive!"
Control flow (2)
n Notes:
n blocks delimited by indentation!
n colon (:) used at end of lines
containing control flow keywords
Control flow (3)
n while loops

a = 10
while a > 0:
print a
a -= 1
Control flow (4)
n for loops

for a in range(10):
print a

n really a "foreach" loop


Control flow (5)
n Common for loop idiom:

a = [3, 1, 4, 1, 5, 9]
for i in range(len(a)):
print a[i]
Control flow (6)
n Common while loop idiom:
f = open(filename, "r")
while True:
line = f.readline()
if not line:
break
# do something with line
Aside 2: file iteration

Instead of using while loop to iterate


n

through file, can write:


f = open("some_file", "r")
for line in f:
# do something with line...

n More concise, generally considered better


Control flow (7): odds & ends
n continue statement like in C
a = 0
while a < 10:
a += 1
if a % 2 == 0:
continue # to next iteration
else:
print a
Control flow (7): odds & ends
n pass keyword:
if a == 0:
pass # do nothing
else:
# whatever
Defining functions
def foo(x):
y = 10 * x + 2
return y
n All variables are local unless
specified as global
n Arguments passed by value
Executing functions
def foo(x):
y = 10 * x + 2
return y

print foo(10) # 102


Comments
n Start with # and go to end of line

n What about C, C++ style comments?


n NOT supported!
Writing standalone scripts
n Can execute any file like this:
% python myprog.py
n Might want file to be directly executable, so...
n at top of file, write this:
#! /usr/bin/env python
# code goes here...
n Then make file executable:
% chmod +x myprog.py
% myprog.py
File naming conventions

n python files usually end in .py


n but executable files usually don’t have
the .py extension
n modules (later) should always have
the .py extension
Take a deep breath...
n Almost done! ;-)
n More on strings
n Modules
n Command-line arguments
n File I/O
Strings and formatting
i = 10
d = 3.1415926
s = "I am a string!"
print "%d\t%f\t%s" % (i, d, s)
print "no newline",
Modules (1)
n Access other code by importing modules
import math
print math.sqrt(2.0)
n or:
from math import sqrt
print sqrt(2.0)
Modules (2)
n or:
from math import *
print sqrt(2.0)
n Can import multiple modules on one line:
import sys, string, math
n Only one "from x import y" per line
Modules (3)
n NOTE!
from some_module import *
n should be avoided
n dumps all names from some_module into
local namespace
n easy to get inadvertent name conflicts this way
Modules (4)
n Code you write in file foo.py is part of module
"foo"

n Can import this code from within other files:


import foo
# code that uses stuff from foo
Command-line arguments
import sys
print len(sys.argv) # NOT argc
# Print all arguments:
print sys.argv
# Print all arguments but the program
# or module name:
print sys.argv[1:] # "array slice"
File I/O
f = open("foo", "r")
line = f.readline()
print line,
f.close()
# Can use sys.stdin as input;
# Can use sys.stdout as output.
Whew!
n First assignment is easy

n Next week: classes and objects

You might also like