CS 11 C track: lecture 1 - Caltech


CS 11 C track: lecture 1 - Caltech

Assignmentsn 1st assignment is posted nown Due one week after class, midnight

Textbookn None requiredn "Learning Python" by Mark Lutzn Most people learn from online docsn links on web site

Why learn Python?n "Scripting language"n Very easy to learnn Interactive front-end for C/C++ coden Object-orientedn Powerful, scalablen Lots of librariesn Fun to use

Python syntaxn Much of it is similar to C syntaxn Exceptions:n missing operators: ++, --n no {} for blocks; uses whitespacen different keywordsn lots of extra featuresn no type declarations!

Starting and exiting Python% pythonPython 2.7.2 ...>>> print "hello"hello>>> ^D%

Simple data typesn Numbersn integern floating-pointn complex!n Stringsn characters are strings of length 1n Booleans are 0/1 (or False/True)

Simple data types: operatorsn + - * / % (like C)n += -= etc. (no ++ or --)n Assignment using =n but semantics are different!a = 1a = "foo" # OKn Can also use + to concatenate strings

Compound data types (1)n Lists:a = [1, 2, 3, 4, 5]print a[1] # 2some_list = []some_list.append("foo")some_list.append(12)print len(some_list) # 2

Compound data types (2)n Dictionaries:n like an array indexed by a stringd = { "foo" : 1, "bar" : 2 }print d["bar"] # 2some_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] # 2empty_tuple = ()n Difference between lists and tuples:n lists are mutable; tuples are immutablen lists can expand, tuples can’tn tuples are slightly faster

Compound data types (4)nnObjects:class Thingy:# next week’s lecturet = Thingy()t.method()print t.fieldBuilt-in data structures (lists, dictionaries)are also objectsnthough internal representation is different

Control flow (1)n if, if/else, if/elif/elseif 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 linescontaining control flow keywords

Control flow (3)n while loopsa = 10while a > 0:print aa -= 1

Control flow (4)n for loopsfor a in range(10):print an 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 iterationn Instead of using while loop to iteratethrough 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 & endsn continue statement like in Ca = 0while a < 10:a += 1if a % 2 == 0:continue # to next iterationelse:print a

Control flow (7): odds & endsn pass keyword:if a == 0:pass # do nothingelse:# whatever

Defining functionsdef foo(x):y = 10 * x + 2return yn All variables are local unlessspecified as globaln Arguments passed by value

Executing functionsdef foo(x):y = 10 * x + 2return yprint foo(10) # 102

Commentsn Start with # and go to end of linen What about C, C++ style comments?n NOT supported!

Writing standalone scriptsnnnnCan execute any file like this:% python myprog.pyMight want file to be directly executable, so...at top of file, write this:#! /usr/bin/env python# code goes here...Then make file executable:% chmod +x myprog.py% myprog.py

File naming conventionsn python files usually end in .pyn but executable files usually don’t havethe .py extensionn modules (later) should always havethe .py extension

Take a deep breath...n Almost done! ;-)n More on stringsn Modulesn Command-line argumentsn File I/O

Strings and formattingi = 10d = 3.1415926s = "I am a string!"print "%d\t%f\t%s" % (i, d, s)print "no newline",

Modules (1)n Access other code by importing modulesn or:import mathprint math.sqrt(2.0)from math import sqrtprint 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, mathn Only one "from x import y" per line

Modules (3)n NOTE!from some_module import *n should be avoidedn dumps all names from some_module intolocal namespacen easy to get inadvertent name conflicts this way

Modules (4)nCode you write in file foo.py is part of module"foo"nCan import this code from within other files:import foo# code that uses stuff from foo

Command-line argumentsimport sysprint 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/Of = 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 easyn Next week: classes and objects

More magazines by this user
Similar magazines