Professional Documents
Culture Documents
FOSSEE
Department of Aerospace Engineering IIT Bombay
Basic Python
1 / 108
Outline
1 2 3 4 5 6 7 8 9 10 11 12 13
The Language The Interpreter Basic Datatypes and Operators Strings Conditionals Loops Lists I/O Files Functions Tuples Dictionaries Sets
FOSSEE (IIT Bombay) Basic Python 2 / 108
The Language
Outline
1 2 3 4 5 6 7 8 9 10 11 12 13
The Language The Interpreter Basic Datatypes and Operators Strings Conditionals Loops Lists I/O Files Functions Tuples Dictionaries Sets
FOSSEE (IIT Bombay) Basic Python 3 / 108
The Language
Python!
Programming Language Powerful, High-level, Interpreted, Multi-Platform Elegant and highly readable syntax Efcient high-level data structures Easy to learn Allows to concentrate on the problem instead of the language Increased Productivity Guido van Rossum BDFL Conceived in December 1989 Named after Monty Pythons Flying Circus, a 70s comedy
FOSSEE (IIT Bombay) Basic Python 4 / 108
The Language
Why Python?
Extremely readable; Forces programmers to write readable code. Interactive; Offers a very fast edit-test-debug cycle. Doesnt get in your way; High-level data structures let you focus on the problem Handles memory management Batteries included; Huge standard library for wide range of tasks. Object-oriented. C, C++ and FORTRAN interfacing allows use of legacy code Your time is more valuable than machine time!
Basic Python
5 / 108
The Interpreter
Outline
1 2 3 4 5 6 7 8 9 10 11 12 13
The Language The Interpreter Basic Datatypes and Operators Strings Conditionals Loops Lists I/O Files Functions Tuples Dictionaries Sets
FOSSEE (IIT Bombay) Basic Python 6 / 108
The Interpreter
Python interpreter
Lets get our hands dirty! Start Python from your shell
$ python Python 2.7.1 (r271:86832, Feb 21 2011, 01:28:26) [GCC 4.5.2 20110127 (prerelease)] on linux2 Type "help", "copyright", "credits" or "license" >>>
First line shows Python version (2.7.1)
The Interpreter
Hello World!
Basic Python
8 / 108
The Interpreter
Versions
Before moving on . . . Currently has two stable branches or versions, 2.x and 3.x 3.x is not backward compatible 3.x is deemed to be the future of Python But, we shall stick to 2.x for this course The ecosystem around Python 2.x hasnt yet moved to 3.x
Basic Python
9 / 108
The Interpreter
IPython
Invoking IPython
An enhanced Python interpreter Tab-completion, Easier access to help, Better history
$ ipython
If ipython is not installed, you need to install it! The prompt is In [1]: instead of >>>
In stands for input, 1 indicates the command number Try Hello World In []: print Hello, World! Out[]: Hello, World!
the numbers have been omitted to avoid confusion
The Interpreter
IPython
Getting comfortable
In In In In
1 5 7 6
+ *
2 3 4 5
Basic Python
11 / 108
The Interpreter
IPython
Change the print 1+2 Use <UP-Arrow> to go back to 1+2 command Use <LEFT-Arrow> to get to start of line; type print Hit <RETURN>
In []: print 1 + 2
Now, change the previous command to print 10*2
Basic Python
12 / 108
The Interpreter
IPython
Tab-Completion
In []: ro<TAB>
Type r, and hit <TAB> All possibilities are listed out, when ambiguous
Basic Python
13 / 108
The Interpreter
IPython
? for Help
To get help for abs function
Basic Python
14 / 108
The Interpreter
IPython
? for Help
To get help for abs function
Basic Python
15 / 108
The Interpreter
IPython
Interrupting
Basic Python
16 / 108
Outline
1 2 3 4 5 6 7 8 9 10 11 12 13
The Language The Interpreter Basic Datatypes and Operators Strings Conditionals Loops Lists I/O Files Functions Tuples Dictionaries Sets
FOSSEE (IIT Bombay) Basic Python 17 / 108
Basic Datatypes
Numbers
int oat complex
Boolean Sequence
Strings Lists Tuples
Basic Python
18 / 108
int
In []: a = 13 In []: a a is a variable of the int type Use the type command to verify In []: type(a)
Integers can be arbitrarily long
Basic Python
19 / 108
float
Basic Python
20 / 108
complex
In []: c = 3+4j
A complex number with real part 3, imaginary part 4
Basic Python
21 / 108
Operations on numbers
In []: 23 + 74 In []: 23 - 56 In []: 45 * 76 In []: 8 / 3 In []: 8.0 / 3 In []: float(8) / 3
The rst division is an integer division To avoid integer division, at least one number should be oat float function is changing int to oat
In []: c = c / 3
An operation like the one above, may equivalently be written as
In []: c /= 3
FOSSEE (IIT Bombay) Basic Python 23 / 108
In In In In In In
t t f f f f
Multiple operation in a single command We use parenthesis for explicitly stating what we mean No discussion of operator precedence
Sequences
Hold a bunch of elements in a sequence Elements are accessed based on position in the sequence The sequence data-types
str list tuple
Basic Python
25 / 108
Basic Python
26 / 108
Operations on Sequences
Accessing elements
Operations on Sequences . . .
Check for container-ship of elements
In In In In
In []: num_list[1:5]
Stride over a sequence
In []: num_list[1:8:2]
FOSSEE (IIT Bombay) Basic Python 28 / 108
Strings
Outline
1 2 3 4 5 6 7 8 9 10 11 12 13
The Language The Interpreter Basic Datatypes and Operators Strings Conditionals Loops Lists I/O Files Functions Tuples Dictionaries Sets
FOSSEE (IIT Bombay) Basic Python 29 / 108
Strings
Anything quoted is a string Single quotes, double quotes or triple single/double quotes Any length single character, null string, . . .
This is a string "This is a string too This is a string as well """This is also a string""" # empty string
Basic Python
30 / 108
Strings
Why so many?
In[]: "Pythons strings are powerful!" In[]: He said, "I love Python!"
Triple quoted strings can be multi-line Used for doc-strings
Basic Python
31 / 108
Strings
Basic Python
32 / 108
Strings
Accessing Elements
In[]: a[0] = H
Strings are immutable!
Basic Python
33 / 108
Strings
Basic Python
34 / 108
Strings
Slicing
Basic Python
35 / 108
Strings
Striding
Basic Python
36 / 108
Strings
String Methods
Basic Python
37 / 108
Strings
Basic Python
38 / 108
Strings
Given a list of strings We wish to join them into a single string Possibly, each string separated by a common token
In[]:
In[]: In[]:
Basic Python
39 / 108
Conditionals
Outline
1 2 3 4 5 6 7 8 9 10 11 12 13
The Language The Interpreter Basic Datatypes and Operators Strings Conditionals Loops Lists I/O Files Functions Tuples Dictionaries Sets
FOSSEE (IIT Bombay) Basic Python 40 / 108
Conditionals
if-else block
A code block : and indentation Exactly one block gets executed in the if-else
Basic Python
41 / 108
Conditionals
if-elif-else
In[]: if a > 0: ....: print "positive" ....: elif a < 0: ....: print "negative" ....: else: ....: print "zero"
Only one block gets executed, depending on a
Basic Python
42 / 108
Conditionals
else is optional
if user == admin: admin_Operations() elif user == moderator: moderator_operations() elif user == client: customer_operations()
Basic Python
43 / 108
Conditionals
Ternary operator
score_str is either AA or a string of one of the numbers
in the range 0 to 100. We wish to convert the string to a number using int Convert it to 0, when it is AA
if-else construct or the ternary operator In[]: if score_str != AA: ....: score = int(score_str) ....: else: ....: score = 0 In[]: ss = score_str In[]: score = int(ss) if ss != AA else 0
FOSSEE (IIT Bombay) Basic Python 44 / 108
Conditionals
pass
Basic Python
45 / 108
Loops
Outline
1 2 3 4 5 6 7 8 9 10 11 12 13
The Language The Interpreter Basic Datatypes and Operators Strings Conditionals Loops Lists I/O Files Functions Tuples Dictionaries Sets
FOSSEE (IIT Bombay) Basic Python 46 / 108
Loops
while
Basic Python
47 / 108
Loops
for
Print squares of all odd numbers less than 10 using for
In[]: ....:
for iterates over each element of a sequence In[]: ....: In[]: ....: for n in [1, 3, 5, 7, 9]: print n*n for n in range(1, 10, 2): print n*n
Loops
break
breaks out of the innermost loop. Squares of odd numbers below 10 using while & break
Basic Python
49 / 108
Loops
continue
Skips execution of rest of the loop on current iteration Jumps to the end of this iteration Squares of all odd numbers below 10, not multiples of 3
Basic Python
50 / 108
Lists
Outline
1 2 3 4 5 6 7 8 9 10 11 12 13
The Language The Interpreter Basic Datatypes and Operators Strings Conditionals Loops Lists I/O Files Functions Tuples Dictionaries Sets
FOSSEE (IIT Bombay) Basic Python 51 / 108
Lists
Creating Lists
In[]: empty = [] In[]: p = [spam, eggs, 100, 1.234] In[]: q = [[4, 2, 3, 4], and, 1, 2, 3, 4]
Lists can be empty, with no elements in them Lists can be heterogeneous every element of different kind
Basic Python
52 / 108
Lists
Accessing Elements
print p[0], p[1], p[3] print p[-1], p[-2], p[-4] print p[10]
Indexing starts from 0 Indexes can be negative Indexes should be in the valid range
Basic Python
53 / 108
Lists
In[]:
In[]: print p[-1], p[-2], p[-4] In[]: print len(p) In[]: print p[10]
Indexing starts from 0 Indexes can be negative Indexes should be within the range(0, len(p))
Basic Python
54 / 108
Lists
Lists
Concatenating lists
In[]: c = a + b In[]: c
Basic Python
56 / 108
Lists
In[]: num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, In[]: num[1:10:2] In[]: num[:10] In[]: num[10:] In[]: num[::2] In[]: num[::-1]
Basic Python
57 / 108
Lists
Sorting
sort method sorts the list in-place Use sorted if you require a new list In[]: In[]: In[]: a = [5, 1, 6, 7, 7, 10] sorted(a) a
Basic Python
58 / 108
Lists
Reversing
reverse method reverses the list in-place Use [::-1] if you require a new list In[]: In[]: In[]: a = [5, 1, 6, 7, 7, 10] a[::-1] a
Basic Python
59 / 108
I/O
Outline
1 2 3 4 5 6 7 8 9 10 11 12 13
The Language The Interpreter Basic Datatypes and Operators Strings Conditionals Loops Lists I/O Files Functions Tuples Dictionaries Sets
FOSSEE (IIT Bombay) Basic Python 60 / 108
I/O
Printing
In[]: In[]: In[]: a = "This is a string" a print a
Both a, and print a are showing the value What is the difference? Typing a shows the value; print a prints it Typing a shows the value only in interpreter In a script, it has no effect.
I/O
String formatting
In[]: x = 1.5 In[]: y = 2 In[]: z = "zed" In[]: print "x is %2.1f y is %d z is %s" %(x,
Basic Python
62 / 108
I/O
In[]: print "Hello" In[]: print "World" In[]: print "Hello", In[]: print "World"
Run the script using % run print_example.py
Basic Python
63 / 108
I/O
raw_input
In[]:
ip = raw_input()
The cursor is blinking; waiting for input Type an input and hit <ENTER>
In[]: print ip
Basic Python
64 / 108
I/O
raw_input . . .
In[]: c = raw_input() In[]: 5.6 In[]: c In[]: type(c) raw_input always takes a string
In[]: name = raw_input("Please enter your name George raw_input can display a prompt string for the user
Basic Python
65 / 108
Files
Outline
1 2 3 4 5 6 7 8 9 10 11 12 13
The Language The Interpreter Basic Datatypes and Operators Strings Conditionals Loops Lists I/O Files Functions Tuples Dictionaries Sets
FOSSEE (IIT Bombay) Basic Python 66 / 108
Files
Opening les
Basic Python
67 / 108
Files
In[]: type(pend) In[]: pend_list = pend.splitlines() In[]: pend_list pend is a string variable
We can split it at the newline characters into a list of strings Close the le, when done; Also, if you want to read again
Files
Reading line-by-line
Basic Python
69 / 108
Files
A;010002;ANAND R;058;037;42;35;40;212;P;;
File with records like the one above is given Each record has elds separated by ; region code; roll number; name; marks 1st L; 2nd L; math; science; social; total pass/fail indicated by P/F; W if withheld and else empty We wish to calculate mean of math marks in region B
Basic Python
70 / 108
Files
Tokenization
In[]: In[]:
string"
Original string is split on white-space (if no argument) Returns a list of strings It can be given an argument to split on that argrument
Basic Python
71 / 108
Files
Tokenization . . .
Since we split on commas, elds may have extra spaces at ends We can strip out the spaces at the ends
"
Basic Python
72 / 108
Files
str to float
After tokenizing, the marks we have are strings We need numbers to perform math operations
In[]: mark_str = "1.25" In[]: mark = int(mark_str) In[]: type(mark_str) In[]: type(mark) strip is returning a new string
Basic Python
73 / 108
Files
Functions
Outline
1 2 3 4 5 6 7 8 9 10 11 12 13
The Language The Interpreter Basic Datatypes and Operators Strings Conditionals Loops Lists I/O Files Functions Tuples Dictionaries Sets
FOSSEE (IIT Bombay) Basic Python 75 / 108
Functions
Abstracting
Reduce duplication of code Fewer lines of code and hence lesser scope for bugs Re-usability of code, thats already been written Use functions written by others, without exactly knowing how they do, what they are doing Enter Functions!
Basic Python
76 / 108
Functions
Dening functions
Consider the function f(x) = x^2 Lets write a Python function, equivalent to this
In[]: def f(x): ....: return x*x ....: In[]: f(1) In[]: f(2) def is a keyword f is the name of the function x the parameter of the function return is a keyword; species what should be returned
FOSSEE (IIT Bombay) Basic Python 77 / 108
Functions
Dening functions . . .
In[]: ....: ....: In[]: def greet(): print "Hello World!"
greet()
avg(12, 10)
Basic Python 78 / 108
Functions
Doc-strings
Its highly recommended that all functions have documentation We write a doc-string along with the function denition
In[]:
def avg(a, b): """ avg takes two numbers as input and returns their average""" return (a + b)/2
avg? greet?
Basic Python
79 / 108
Functions
In[]:
def circle(r): """returns area and perimeter of a circle given, the radius r""" pi = 3.14 area = pi * r * r perimeter = 2 * pi * r return area, perimeter
Functions
What? 1
Basic Python
81 / 108
Functions
What? 2
Basic Python
82 / 108
Functions
Default arguments
In[]: round(2.484) In[]: round(2.484, 2) In[]: In[]: s.split() # split on spaces s.split(;) # split on ;
In[]: range(10) # returns numbers from 0 to 9 In[]: range(1, 10) # returns numbers from 1 to In[]: range(1, 10, 2) # returns odd numbers fro
Basic Python
83 / 108
Functions
Default arguments . . .
In[]: ....: ....: def welcome(greet, name="World"): print greet, name
Basic Python
84 / 108
Functions
Keyword Arguments
In[]: ....: ....: In[]: def welcome(greet, name="World"): print greet, name
welcome("Hello", "James")
Basic Python
85 / 108
Functions
Built-in functions
abs, any, all, len, max, min pow, range, sum, type Refer here: http: //docs.python.org/library/functions.html
Basic Python
86 / 108
Functions
Variable Scope
In[]: def change(q): ....: q = 10 ....: print q ....: In[]: In[]: change(1) print q
Basic Python
87 / 108
Functions
Variable Scope
In[]: def change(): ....: global n ....: n = 10 ....: print n ....: In[]: change() In[]: Bombay) print n FOSSEE (IIT Basic Python
88 / 108
Functions
Variable Scope
global
Basic Python
89 / 108
Functions
Variable Scope
Mutable variables
Behavior is different when assigning to a list element/slice Python looks up for the name, from innermost scope outwards, until the name is found
In[]: name = [Mr., Steve, Gosling] In[]: def change_name(): ....: name[0] = Dr. ....: In[]: change_name() In[]: print name
Basic Python
90 / 108
Functions
Variable Scope
Passing Arguments . . .
In[]: In[]: ....: ....: ....: In[]: In[]: In[]: In[]: ....: ....: ....: In[]: In[]: n = 5 def change(n): n = 10 print "n = %s inside change " %n change(n) print n
name = [Mr., Steve, Gosling] def change_name(n): n[0] = Dr. print "n = %s inside change_name" %n change_name(name) print name
Basic Python 91 / 108
Tuples
Outline
1 2 3 4 5 6 7 8 9 10 11 12 13
The Language The Interpreter Basic Datatypes and Operators Strings Conditionals Loops Lists I/O Files Functions Tuples Dictionaries Sets
FOSSEE (IIT Bombay) Basic Python 92 / 108
Tuples
Tuples Initialization
In[]: In[]:
In[]: In[]:
a = 1, 2, 3 b = 1,
Basic Python
93 / 108
Tuples
Indexing
Basic Python
94 / 108
Tuples
Swapping values
In[]: In[]: In[]: In[]: In[]: a = 5 b = 7 temp = a a = b b = temp
In[]:
a, b = b, a
a = 2.5 b = "hello" a, b = b, a
Basic Python 95 / 108
Tuples
In[]:
a, b = b, a
Basic Python
96 / 108
Dictionaries
Outline
1 2 3 4 5 6 7 8 9 10 11 12 13
The Language The Interpreter Basic Datatypes and Operators Strings Conditionals Loops Lists I/O Files Functions Tuples Dictionaries Sets
FOSSEE (IIT Bombay) Basic Python 97 / 108
Dictionaries
Creating Dictionaries
In[]: In[]: mt_dict = {}
extensions = {jpg : JPEG Image, py : Python script, html : Html document, pdf : Portable Document Form extensions
In[]:
Basic Python
98 / 108
Dictionaries
Accessing Elements
In[]:
print extensions[jpg]
In[]:
print extensions[zip]
Basic Python
99 / 108
Dictionaries
Dictionaries
Containership
Basic Python
101 / 108
Dictionaries
In[]: for each in extensions.keys(): ....: print each, "-->", extensions[each] ....:
Basic Python
102 / 108
Sets
Outline
1 2 3 4 5 6 7 8 9 10 11 12 13
The Language The Interpreter Basic Datatypes and Operators Strings Conditionals Loops Lists I/O Files Functions Tuples Dictionaries Sets
FOSSEE (IIT Bombay) Basic Python 103 / 108
Sets
Creating Sets
Conceptually identical to the sets in mathematics Duplicate elements not allowed No ordering of elements exists
Basic Python
104 / 108
Sets
Operations on Sets
In[]: In[]: f10 = set([1, 2, 3, 5, 8]) p10 = set([2, 3, 5, 7])
In[]:
Intersection
In[]:
Difference
In[]: In[]:
FOSSEE (IIT Bombay)
Symmetric Difference
Sets
Sub-sets
Proper Subset
In[]: In[]:
Subsets
In[]:
Basic Python
106 / 108
Sets
Elements of sets
Containership
In[]: In[]:
1 in f10 4 in f10
In[]:
Basic Python
107 / 108
Sets
Sets Example
Given a list of marks, [20, 23, 22, 23, 20, 21, 23] list all the duplicates
marks = [20, 23, 22, 23, 20, 21, 23] marks_set = set(marks) for mark in marks_set: marks.remove(mark)
Basic Python
108 / 108