0% found this document useful (0 votes)
20 views155 pages

Weeks 4 To 7

The document outlines a 10-week Python course structure, including assignments, tests, and a final project. It covers the history, syntax, and various features of Python, emphasizing its versatility and importance in fields like data science and machine learning. Additionally, it introduces key concepts such as variable types, operators, and data structures like tuples, strings, and lists.

Uploaded by

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

Weeks 4 To 7

The document outlines a 10-week Python course structure, including assignments, tests, and a final project. It covers the history, syntax, and various features of Python, emphasizing its versatility and importance in fields like data science and machine learning. Additionally, it introduces key concepts such as variable types, operators, and data structures like tuples, strings, and lists.

Uploaded by

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

Introduction to Python

Structure
• 10 Weeks of Python (Starting 4th week till 13th week)

• Python:
• 4 take home weekly assignments best 3 to be taken (27%)
• 22nd Sep,
• 6th Oct,
• 20th Oct,
• 3rd Nov
• 2 in-class coding tests (18%)
• 25th Oct
• 15th Nov
• Final project (25%)
• Given on 17th Nov, to be submitted by 1st Dec
Weeks 4 to 7
Why Python?
• Why do you want to learn Python/programming?
• What would you use Python for?
Why Python?
Python History

• Started by Guido Van Rossum as a hobby


• Now widely spread
• Open Source! Free!
• Versatile

Source: https://bootcamp.berkeley.edu/blog/most-in-demand-
programming-languages/
Python Today
• A large and active scientific computing and data analysis community
• Now one of the most important languages for
• Data science, Machine learning, Deep Learning (rapid prototyping)
• Towards Enterprise Application Development
• Packages: NumPy, pandas, matplotlib, SciPy, scikit-learn, statsmodels,
etc.
What is python?
• Object oriented language
• Interpreted language
• (Initial Source code, Intermediate Byte Code, Execution
in Virtual Machine)
• Supports dynamic data type
• Independent from platforms
• Focused on development time
• Simple and easy grammar
• Automatic memory management
• It’s free (open source)!
Python Syntax
• Much of it is similar to C syntax
• Exceptions:
• missing operators: ++, --
• no curly brackets,{}, for blocks; uses whitespace
• different keywords
• lots of extra features
• no type declarations!
Modes of Use
1. Ipython / Jupyter Notebook
Python can be run interactively
Used extensively in research

2. Other IDEs
PyCharm
Jupyter Notebook

• Easy to use environment


• Web-based
• Come with a great number of
useful packages
Starting a Notebook
Toolbar

Stop
Save Cut, copy execution Block type
paste
New block Move block Reset block
And clear output
Kernel/Restart & Clear output
Running blocks
• By pressing the Run button
• Shift + Enter – runs block
• Alt + Enter – creates a new block
Commenting
• Useful when your code needs further explanation. Either for your
future self and anybody else.
• Useful when you want to remove the code from execution but not
permanently
• Comments in Python are done with #
Variables and Operators
Python as a calculator
• Distance between Edinburgh and London is 403 miles.
• Let us calculate the distance between Edinburgh and London in km
Why We Need Variables?
• Great calculator but how can we make it store values?
• Yes by defining variables
• Can later be called by the variable name
• Variable names are case sensitive and unique
Why We Need Variables?
We can now reuse the variable mileToKm in the next block without
having to define it again!
Type of Variables
• Python is both a strongly typed and a dynamically typed language.
• Strong typing means that variables do have a type and that the type matters when
performing operations on a variable.
• Dynamic typing means that the type of the variable is determined only during runtime.
• Due to strong typing, types need to be compatible with respect to the operand when
performing operations. For example Python allows one to add an integer and a floating
point number, but adding an integer to a string produces error.
• friendly = 1
if (friendly):
greeting = "hello world"
else:
greeting = 12**2
print (greeting)
• Everything is a variable:
• functions, modules, classes
Variable Naming Rules
• Names are case sensitive and cannot start with a number. They can
contain letters, numbers, and underscores.
bob Bob _bob _2_bob_ bob_2 BoB

• There are some reserved words:


and, assert, break, class, continue, def, del, elif,
else, except, exec, finally, for, from, global, if,
import, in, is, lambda, not, or, pass, print, raise,
return, try, while
Variable Naming conventions
The Python community has these recommend-ed naming conventions
•joined_lower for functions, methods and, attributes
•joined_lower or ALL_CAPS for constants
•StudlyCaps for classes
•camelCase only to conform to pre-existing conventions
•Attributes: interface, _internal, __private
Assignment
• You can assign to multiple names at the same time
>>> x, y = 2, 3
>>> x
2
>>> y
3
This makes it easy to swap values
>>> x, y = y, x
• Assignments can be chained
>>> a = b = x = 2
Variable Reference Semantics
• Assignment manipulates references
• x = y does not make a copy of y
• x = y makes x reference the object y references
• Very useful; but beware!
• Example:
a = [1, 2, 3];
b=a
a.append(4);
print (b)
[1, 2, 3, 4]
Variable Types
Variables have a type, which defines the way it is stored.
The basic types are:
Why should we care about variable types?

Important lesson to remember!


We can't do arithmetic operations on variables of different types. Therefore make sure that you are
always aware of your variables types!

You can find the type of a variable using type(). For example type type(x).
Casting Variable Types
Python offers us a way of converting variables to different types!
Casting is the operation of converting a variable to a different type

Similar methods exist for other


data types: int(), float(), str()
Quiz

What will be the result (30 or 1020)?


Arithmetic Operations

Similar to actual Mathematics.


Order of precedence is the same as
in Mathematics (BODMASS).

We can also use parenthesis ()


Precedence of Operators

https://techvidvan.com/tutorials/python-operator-precedence/
Order precedence example
(16 ** 2) / 4
Comparison operators
• I.e. comparison operators
• Return Boolean values
(i.e. True or False)
• Used extensively for
conditional statements
Comparison examples

False
Logical operators

• Allows us to extend the conditional logic


• Will become essential later on
Combining both

True True
Another example

True True True

That wasn't very easy to read was it?


Is there a way we can make it more readable?
Another example
Quiz

vs
Quiz

vs

13 49
Sequences or Ordered Data Structures:
Tuples, Strings, and Lists
Sequence Types
1. Tuple: (‘john’, 32, [‘APU’])
· A simple immutable ordered sequence of
items
· Items can be of mixed types, including
collection types
2. Strings: “John Smith”
• Immutable
• Conceptually very much like a tuple
3. List: [1, 2, ‘john’, (‘up’, ‘down’)]
· Mutable ordered sequence of items of mixed
types
Similar Syntax
• All three sequence types (tuples, strings, and lists) share
much of the same syntax and functionality.
• Key difference:
• Tuples and strings are immutable
• Lists are mutable
• The operations shown in this section can be applied to all
sequence types
• most examples will just show the operation performed on
one
Sequence Types 1
• Define tuples using parentheses and commas
>>> tu = (23, ‘abc’, 4.56, (2,3),
‘def’)
• Define lists are using square brackets and commas
>>> li = [“abc”, 34, 4.34, 23]
• Define strings using quotes (“, ‘, or “““).
>>> st = “Hello World”
>>> st = ‘Hello World’
>>> st = “““This is a multi-line
string that uses triple quotes.”””
Sequence Types 2
• Access individual members of a tuple, list, or string
using square bracket “array” notation
• Note that all are 0 based…
>>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> tu[1] # Second item in the tuple.
‘abc’

>>> li = [“abc”, 34, 4.34, 23]


>>> li[1] # Second item in the list.
34

>>> st = “Hello World”


>>> st[1] # Second character in string.
‘e’
Positive and negative indices
>>> t = (23, ‘abc’, 4.56, (2,3),
‘def’)
Positive index: count from the left, starting with 0
>>> t[1]
‘abc’
Negative index: count from right, starting with –1
>>> t[-3]
4.56
Slicing: return copy of a subset
>>> t = (23, ‘abc’, 4.56, (2,3),
‘def’)

Return a copy of the container with a subset of the


original members. Start copying at the first index,
and stop copying before second.
>>> t[1:4]
(‘abc’, 4.56, (2,3))
Negative indices count from end
>>> t[1:-1]
(‘abc’, 4.56, (2,3))
Slicing: return copy of a subset
>>> t = (23, ‘abc’, 4.56, (2,3),
‘def’)
Omit first index to make copy starting from beginning
of the container
>>> t[:2]
(23, ‘abc’)
Omit second index to make copy starting at first index
and going to end
>>> t[2:]
(4.56, (2,3), ‘def’)
Copying the Whole Sequence
• [ : ] makes a copy of an entire sequence
>>> t[:]
(23, ‘abc’, 4.56, (2,3), ‘def’)
• Note the difference between these two lines for
mutable sequences
>>> l2 = l1 # Both refer to 1 ref,
# changing one affects
both
>>> l2 = l1[:] # Independent copies,
two refs
The ‘in’ Operator
• Boolean test whether a value is inside a container:
>>> t = [1, 2, 4, 5]
>>> 3 in t
False
>>> 4 in t
True
>>> 4 not in t
False

• For strings, tests for substrings


>>> a = 'abcde'
>>> 'c' in a
True
>>> 'cd' in a
True
>>> 'ac' in a
False

• Be careful: the in keyword is also used in the syntax of for loops and list
comprehensions
The + Operator

The + operator produces a new tuple, list, or string whose value is the concatenation of
its arguments.

>>> (1, 2, 3) + (4, 5, 6)


(1, 2, 3, 4, 5, 6)

>>> [1, 2, 3] + [4, 5, 6]


[1, 2, 3, 4, 5, 6]

>>> “Hello” + “ ” + “World”


‘Hello World’
The * Operator

• The * operator produces a new tuple, list, or string that “repeats” the
original content.

>>> (1, 2, 3) * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)

>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

>>> “Hello” * 3
‘HelloHelloHello’
Tuples
• What is a tuple?
• A tuple is an ordered collection which cannot
be modified once it has been created.
• In other words, it's a special array, a read-only array.
• How to make a tuple? In round brackets
• E.g.,
>>> t = ()
>>> t = (1, 2, 3)
>>> t = (1, )
>>> t = 1,
>>> a = (1, 2, 3, 4, 5)
>>> print a[1] # 2
Tuples
• Effectively lists that are immutable (I.e. can't be changed)
Tuples
• The comma is the tuple creation operator, not parens
>>> 1,
(1,)

• Python shows parens for clarity (best practice)


>>> (1,)
(1,)

• Don't forget the comma!


>>> (1)
1

• Trailing comma only required for singletons others


• Empty tuples have a special syntactic form
>>> ()
()
>>> tuple()
()
Operations in Tuple
• Indexing e.g., T[i]
• Slicing e.g., T[1:5]
• Concatenation e.g., T + T
• Repetition e.g., T * 5
• Membership test e.g., ‘a’ in T
• Length e.g., len(T)
Strings
• Powerful and flexible in Python
• Can be added
• Can be multiplied
• Can be multiple lines
Strings
Methods in string
• upper()  strip(), lstrip(), rstrip()
• lower()  replace(a, b)
• capitalize()  expandtabs()
• count(s)  split()
• find(s)  join()
• rfind(s)  center(), ljust(), rjust()
• index(s)
Printing
• When writing scripts, your outcomes aren't printed on the terminal.
• Thus, you must print them yourself with the print() function.
• Beware to not mix up the different type of variables!
Strings
X = “Bengaluru”
X = x.upper()
Y = “This is”
Y = y.lower()
y+x

These are called methods and add extra functionality to the String.
If you want to see more methods that can be applied to a string simply
type in dir('str')
Strings and formatting
i = 10
d = 3.1415926
s = "I am a string!"
print ("%d\t%f\t%s" % (i, d, s))
print (“newline\n“)
print ("no newline“)
Mixing up strings and numbers
Often we would need to mix up numbers and strings.
It is best to keep numbers as numbers (i.e. int or float)
and cast them to strings whenever we need them as a string.
Multiline strings
Strings
• "hello"+"world" "helloworld" # concatenation
• "hello"*3 "hellohellohello" # repetition
• "hello"[0] "h" # indexing
• "hello"[-1] "o" # (from end)
• "hello"[1:4] "ell" # slicing
• len("hello") 5 # size
• "hello" < "jello" 1 # comparison
• "e" in "hello" 1 # search
• New line: "escapes: \n "
• Line continuation: triple quotes ’’’
• Quotes: ‘single quotes’, "raw strings"
Quiz
Do you see anything wrong with this block?
Another more generic way to fix it

If we comma separate statements in a print function, we can


have different variables printing!
Data structure size
Make sure you are always aware of the sizes of each variable!
This can easily be done using the len() function.
It returns the length/size of any data structure

len(x)
List: A Compound Data Type
• List:
• A container that holds a number of other objects, in a
given order
• Defined in square brackets
a = [1, 2, 3, 4, 5]
print a[1] # number 2
some_list = []
some_list.append("foo")
some_list.append(12)
print len(some_list) # 2
List
• a = [99, "bottles of beer", ["on", "the", "wall"]]
• Flexible arrays, not Lisp-like linked lists
• Same operators as for strings
• a+b, a*3, a[0], a[-1], a[1:], len(a)
• Item and slice assignment
• a[0] = 98
• a[1:2] = ["bottles", "of", "beer"]
• a now is [98, "bottles", "of", "beer", ["on", "the", "wall"]]
• del a[-1]
• a now is [98, "bottles", "of", "beer"]
List
• One of the most useful concepts
• Group multiple variables together (a kind of container!)
Indexing a list
• Indexing – accessing items within a data structure

• Indexing a list is not very intuitive...


• The first element of a list has an index 0
Operations on Lists Only
Lists have many methods, including index, count, remove,
reverse, sort
>>> li = [‘a’, ‘b’, ‘c’, ‘b’]
>>> li.index(‘b’) # index of 1st
occurrence
1
>>> li.count(‘b’) # number of
occurrences
2
>>> li.remove(‘b’) # remove 1st occurrence
>>> li
[‘a’, ‘c’, ‘b’]
Operations on Lists Only
>>> li = [5, 2, 6, 8]

>>> li.reverse() # reverse the list *in place*


>>> li
[8, 6, 2, 5]

>>> li.sort() # sort the list *in place*


>>> li
[2, 5, 6, 8]
Quiz
What will fruits[3] return?
Quiz
What will this return?
Quiz
What will this return?
List Modification

Furthermore, we can modify lists in various ways


Lists with integers
range() - a function that generates a sequence of numbers as a list
Slicing lists
• Slicing – obtain a particular set of sub-elements from a data structure.
• Very useful and flexible.
Lists – helpful functions
• Makes them extremely useful and versatile
Lists can be of different types
• Not very useful, but possible
Operations in List
 append • Indexing e.g., L[i]
 insert • Slicing e.g., L[1:5]
 index • Concatenation e.g., L + L
 count • Repetition e.g., L * 5
 sort
• Membership test e.g., ‘a’ in L
 reverse
• Length e.g., len(L)
 remove
 pop
 extend
More list operations
>>> a = range(5) # [0,1,2,3,4]
>>> a.append(5) # [0,1,2,3,4,5]
>>> a.pop() # [0,1,2,3,4]
5
>>> a.insert(0, 5.5) # [5.5,0,1,2,3,4]
>>> a.pop(0) # [0,1,2,3,4]
5.5
>>> a.reverse() # [4,3,2,1,0]
>>> a.sort() # [0,1,2,3,4]
Nested List
• List in a list
• E.g.,
• >>> s = [1,2,3]
• >>> t = [‘begin’, s, ‘end’]
• >>> t
• [‘begin’, [1, 2, 3], ‘end’]
• >>> t[1][1]
• 2
List comprehensions (2.0)
• Create lists without map(), filter(), lambda
• = expression followed by for clause + zero or more for or of clauses
>>> vec = [2,4,6]
>>> [3*x for x in vec]
[6, 12, 18]
>>> [{x: x**2} for x in vec}
[{2: 4}, {4: 16}, {6: 36}]

Advanced Programming
16 Mar 2025
Spring 2002
List comprehensions
• cross products:
>>> vec1 = [2,4,6]
>>> vec2 = [4,3,-9]
>>> [x*y for x in vec1 for y in vec2]
[8,6,-18, 16,12,-36, 24,18,-54]
>>> [x+y for x in vec1 and y in vec2]
[6,5,-7,8,7,-5,10,9,-3]
>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
[8,12,-54]

Advanced Programming
16 Mar 2025
Spring 2002
List comprehensions
• can also use if:
>>> [3*x for x in vec if x > 3]
[12, 18]
>>> [3*x for x in vec if x < 2]
[]

Advanced Programming
16 Mar 2025
Spring 2002
del – removing list items
• remove by index, not value
• remove slices from list (rather than by assigning an empty list)
>>> a = [-1,1,66.6,333,333,1234.5]
>>> del a[0]
>>> a
[1,66.6,333,333,1234.5]
>>> del a[2:4]
>>> a
[1,66.6,1234.5]

Advanced Programming
16 Mar 2025
Spring 2002
Mutability:
Tuples vs. Lists
List vs. Tuple
• What are common characteristics?
• Both store arbitrary data objects
• Both are of sequence data type
• What are differences?
• Tuple doesn’t allow modification
• Tuple doesn’t have methods
• Tuple supports format strings
• Tuple supports variable length parameter in function call.
• Tuples slightly faster
Summary: Tuples vs. Lists
• Lists slower but more powerful than tuples
• Lists can be modified, and they have lots of handy operations and
methods
• Tuples are immutable and have fewer features
• To convert between tuples and lists use the list() and tuple()
functions:
li = list(tu)
tu = tuple(li)
Mutability
Mutable object – can be changed after creation.

Immutable object - can NOT be changed after creation.


Lists are mutable
>>> li = [‘abc’, 23, 4.34, 23]
>>> li[1] = 45
>>> li
[‘abc’, 45, 4.34, 23]

• We can change lists in place.


• Name li still points to the same memory
reference when we’re done.
Tuples are immutable
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> t[2] = 3.14

Traceback (most recent call last):


File "<pyshell#75>", line 1, in -toplevel-
tu[2] = 3.14
TypeError: object doesn't support item assignment

• You can’t change a tuple.


• You can make a fresh tuple and assign its reference to a
previously used name.
>>> t = (23, ‘abc’, 3.14, (2,3), ‘def’)
• The immutability of tuples means they’re faster than lists.
Operations on Lists Only
>>> li = [1, 11, 3, 4, 5]

>>> li.append(‘a’) # Note the method


syntax
>>> li
[1, 11, 3, 4, 5, ‘a’]

>>> li.insert(2, ‘i’)


>>>li
[1, 11, ‘i’, 3, 4, 5, ‘a’]
The extend method vs +
• + creates a fresh list with a new memory ref
• extend operates on list li in place.
>>> li.extend([9, 8, 7])
>>> li
[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7]

• Potentially confusing:
• extend takes a list as an argument.
• append takes a singleton as an argument.
>>> li.append([10, 11, 12])
>>> li
[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7, [10, 11, 12]]
Data Type Wrap Up
• Lists, Tuples, and Dictionaries can store any type (including other lists,
tuples, and dictionaries!)
• Only lists and dictionaries are mutable
• All variables are references
Quiz
• Which one is mutable: List or Tuple?
Dictionaries
• Dictionaries: curly brackets
• What is dictionary?
• Refer value through key; “associative arrays”
• Like an array indexed by a string
• An unordered set of key: value pairs
• Values of any type; keys of almost any type
• {"name":"Guido", "age":43, ("hello","world"):1,
42:"yes", "flag": ["red","white","blue"]}
d = { "foo" : 1, "bar" : 2 }
print d["bar"] # 2
some_dict = {}
some_dict["foo"] = "yow!"
print some_dict.keys() # ["foo"]
Methods in Dictionary
• keys()
• values()
• items()
• has_key(key)
• clear()
• copy()
• get(key[,x])
• setdefault(key[,x])
• update(D)
• popitem()
Dictionary details
• Keys must be immutable:
• numbers, strings, tuples of immutables
• these cannot be changed after creation
• reason is hashing (fast lookup technique)
• not lists or other dictionaries
• these types of objects can be changed "in place"
• no restrictions on values
• Keys will be listed in arbitrary order
• again, because of hashing
Dictionaries
• Similar to actual dictionaries
• They are effectively 2 lists
combined – keys and values
• We use the keys to access the
values instead of indexing them
like a list
• Each value is mapped to a
unique key
Dictionary definition
Defined as comma separated key : value pairs:

Comma separated

Curly brackets
Dictionary properties
• Each value is mapped to an unique key
• Values are accessed by their key
• Key are unique and are immutable
• Values cannot exist without a key
Dictionaries
Let us define the one from the previous image
Accessing a dictionary
Values are accessed by their keys (just like a dictionary)

Note that they can't be indexed like a list


Altering a dictionary
Can be done via the dictionary methods
Keys and Values
It is possible to obtain only the keys or values of a dictionary.

This is useful for iteration.


Sets
• Effectively lists that can't contain duplicate items
• Sets are mutable
• Similar functionality to lists
• Can't be indexed or sliced
• Can be created with {} or you can convert a list to a set
Quiz
• Are Python dictionary keys and values both mutable?
Flow Control
If Else
• Fundamental building block of software

Conditional statement
Executed if answer is True

Executed if answer is False


If Else example
Try running the example below.
What do you get?
Indentation matters!
• Code is grouped by its indentation
• Indentation is the number of whitespace or tab characters before the code.
• If you put code in the wrong block then you will get unexpected behaviour
Extending if-else blocks
• We can add infinitely more if statements using elif

• elif = else + if which means that the previous statements must be false
for the current one to evaluate to true
Bitcoin broker example
Quiz
• What would happen if both conditions are True?
Control flow
• if, if/else, if/elif/else
if a == 0:
print "zero!"
elif a < 0:
print "negative!"
else:
print "positive!"

 Notes:
• blocks delimited by indentation!
• colon (:) used at end of lines containing control flow keywords
Loops
For loop
• Allows us to iterate over a set amount of variables within a data
structure. During that we can manipulate each item however we want

• Again, indentation is important here!


Example
• Say we want to go over a list and print each item along with its index

• What if we have much more than 4 items in the list, say, 1000?
For example
• Now with a for loop

• Saves us writing more lines


• Doesn't limit us in term of size
Numerical for loop
While loop
• Another useful loop. Similar to the for loop.
• A while loop doesn't run for a predefined number of iterations, like a for
loop. Instead, it stops as soon as a given condition becomes true/false.
Break statement
• Allows us to go(break) out of a loop preliminary.
• Adds a bit of controllability to a while loop.
• Usually used with an if.
• Can also be used in a for loop.
Quick quiz
How many times are we going to execute the while loop?
Quick quiz
How many times are we going to execute the while loop?
Control flow

• while loops

a = 10
while a > 0:
print a
a -= 1
Control flow
• for loops

for a in range(10):
print a
Control flow

• Common for loop idiom:

a = [3, 1, 4, 1, 5, 9]
for i in range(len(a)):
print a[i]
Control flow
• Common while loop idiom:
f = open(filename, "r")
while True:
line = f.readline()
if not line:
break
# do something with line
Control flow: odds & ends

• continue statement like in C


• pass keyword:
if a == 0:
pass # do nothing
else:
# whatever
Functions
Functions
• Allow us to package functionality in a nice and readable way
• reuse it without writing it again
• Make code modular and readable
• Rule of thumb - if you are planning on using very similar code more
than once, it may be worthwhile writing it as a reusable function.
Function declaration
keyword Any number of arguments

[Optional] Exits the function and returns some value

• Functions accept arguments and execute a piece of code


• Often, they also return values (the result of their code)
Function example
Function example 2
We want to make a program that rounds numbers up or down.
Try to pack the following into a function.
Function example 2
Python built-in functions

To find out how they work: https://docs.python.org/3.3/library/functions.html


Defining functions
def foo(x):
y = 10 * x + 2
return y
• All variables are local unless
specified as global
• Arguments passed by value
Executing functions

def foo(x):
y = 10 * x + 2
return y

print foo(10) # 102


Lambda Function
• anonymous functions
• may not work in older versions of Python.
def make_incrementor(n):
return lambda x: x + n

f = make_incrementor(42)
f(0)
f(1)

Advanced Programming
16 Mar 2025
Spring 2002
Exception Handling
• The build-in exceptions in Python are raised when the program
encounters an error.
• When exception occur, the Python interpreter stops executing
the current process and passes the control it the calling process
until it is handled.
• If not handled, the program will crash.
• Some common exceptions are:
• ZeroDivisionError: Occurs when a number is divided by zero.
• NameError: It occurs when a name is not found. It may be local or global.
• IndentationError: If incorrect indentation is given.
• IOError: It occurs when Input Output operation fails.
• EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.
Exception Handling
try :
Try running this code
except:
Run this only if exception occurs
finally:
Always run this
Catching Exceptions
#python code a.py
x = 0
try:
print 1/x
except ZeroDivisionError, message:
print "Can’t divide by zero:"
print message

>>>python a.py
Can't divide by zero:
integer division or modulo by zero
Write a program which asks for 2 numbers and
handles exception when a number is divided by
zero
Pseudocode:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
print("a/b = ",a/b)
except ZeroDivisionError:
print(“This is inside except block”)
print("The value of b can't be 0")
finally:
print(“this is inside finally block and always
executed”)
Modules
Why use modules?
• Code reuse
• Routines can be called multiple times within a program
• Routines can be used from multiple programs
• Namespace partitioning
• Group data together with functions used for that data
• Implementing shared services or data
• Can provide global data structure that is accessed by
multiple subprograms
Modules
• Modules are functions and variables defined in separate files
• Items are imported using from or import
• from module import function
• function()

• import module
• module.function()
• Modules are namespaces
• Can be used to organize variable names, e.g.
• atom.position = atom.position - molecule.position
Modules
• Access other code by importing modules
import math
print math.sqrt(2.0)

• or:
from math import sqrt
print sqrt(2.0)
Modules
• or:
from math import *
print sqrt(2.0)

• Can import multiple modules on one line:


import sys, string, math

• Only one "from x import y" per line


Final Topics and Project Discussions
References for Slides
• Introduction to Python - University of Edinburgh
• Python: An Introduction University of North Carolina Shubin Liu
• Introduction to Python – UMBC CSEE
• Python - Henning Schulzrinne - Department of Computer Science -
Columbia University
Additional References for Python
• Python Homepage
• http://www.python.org
• Python Tutorial
• http://docs.python.org/tutorial/
• Python Documentation
• http://www.python.org/doc
• Python Library References
• http://docs.python.org/release/2.5.2/lib/lib.html
• Python Add-on Packages:
• http://pypi.python.org/pypi
And many others …

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy