0% found this document useful (0 votes)
1 views44 pages

DSAP-Lecture 1 - Python Programming Basics

Uploaded by

ayushij220ain
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)
1 views44 pages

DSAP-Lecture 1 - Python Programming Basics

Uploaded by

ayushij220ain
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/ 44

Introduction to Python

Programming
Data Structures & Algorithms

Lecture 1
Topics to Cover
● Revisiting Basics
○ Python Objects - identifiers
○ Sequence types - Lists, Tuple, Sets, Strings
○ Dictionary Class
○ Operators for Sequences & Dictionaries
○ Polymorphic Functions
○ File Read & Write
● Advanced
○ Exception Handling
○ Iterators & Generators
○ Python Conveniences
○ Scopes & Namespaces
Introduction
● What is Python?

It is an interpreted programming language designed for high readability and


faster prototyping leading to production-ready software development.

● Why Python?
○ Works on multiple platforms - Windows, Linux, Mac etc.
○ Simple syntax similar to English language
○ Write programs with fewer lines compared to other programming language
○ Runs on interpreter - code can be executed as soon as it is written.
● Good to Know
○ Most recent version is Python 3 with some major updates over Python 2.
○ IDES - pyCharm, Eclipse, Jupyter
How and Where to Write Programs?

● Codes could be executed online on Google Colab.


Google Login will be required.

● Create a New Python 3 Notebook: File -> New


Python 3 Notebook

● An Example Program Sheet is provided for


reference here.

● We will use Jupyter Notebook for writing


programs.

● Go through the Google Colab tutorial to


understand more about its use.

● You can also write your codes on other Python


IDEs as well.
Python Introduction
● An interpreted programming language
● # is used for inserting comments
● “”” … “”” or ‘’’ … ‘’’ can be used multi-line comments.
● ‘\’ can be used for continuing command on multiple lines
● A code block is tab indented within a control structure
● An object oriented language and classes form the basis for all data types.
Identifiers
● Identifiers are variable names - case sensitive, combination of letters,numbers and underscores.
● Python identifier is most similar to a reference variable in Java or a pointer variable in C++.
○ Each identifier is implicitly associated with the memory address of the object to which it
refers.
● Python is dynamically typed language as there is no advance declaration associating an identifier
with a particular data type.
Creating and Using Objects 98.6 instantiates a
float-type class

● Create a new instance of a class -


instantiation
● Python literals for designating new instances.
> temperature = 98.6

● Alias: assigning a second identifier to an existing object


> original = temperature

● Python supports various ways of calling


methods:
○ sort(data) # standard call to methods / functions
○ data.sort() # member functions
Types of Methods

● Accessors - return information about the


state of an object, but do not change the
state

● Mutators or update methods: change the


state of the object.

● A class is immutable if each object of that


class has a fixed value upon instantiation
that cannot subsequently be changed.
Example: float, int, bool, str class
Sequence Type Classes
● The list class

● The tuple class

● The str class

● The set / frozenset class


The list class
● A list instance stores a sequence of objects.

● A list is a referential structure - as it technically stores


a sequence of references to its elements.

● Lists are array-based sequences and are > prime = [2,3,5,7,11,13,17,19,23,29,31]

zero-indexed, thus a list of length n has elements


indexed from 0 to n−1 inclusive.

● Python uses the characters [ ] as delimiters for a list


literal, with [ ] itself being an empty list.

● The list() constructor produces an empty list by


default. However, the constructor will accept any
parameter that is of an iterable type.
● The list is a mutable sequence - The elements can be
added or removed from the sequence.
The tuple class

● An immutable version of a sequence. It can not be


changed. Elements can not be added to or
removed from the sequence.

● parentheses () delimit a tuple, with () being an


empty tuple.

● To express a tuple of length one as a literal, a


comma must be placed after the element, but within
the parentheses.
For example, (17,) is a one-element tuple.
The str class

● represents an immutable sequence of characters.

● Examples: “hello”, ‘hello’, “Don’t Worry”, ‘Don\’t worry’,


‘C:\\Python\\’ (notice the escape characters)

● Unicode characters can also be included. E.g.


‘20\u20AC’ for string ‘20€’

● ‘ ’ ’ and “ ” ” for multi-line comments

● Individual characters of the string can be accessed


using [] operator.
The set and frozenset classes
● The set class represents the mathematical notion of a set, namely
a collection of elements, without duplicates, and without an
inherent order to those elements.

● The major advantage of using a set, as opposed to a list, is that it


has a highly optimized method for checking whether a specific
element is contained in the set. It is based on a data structure
called “Hash Tables”.

● It has two restrictions:


○ It does not maintain the elements in any particular order.
○ Only instances of immutable types can be added into a
python set: int, floats, strings, tuples and frozensets.

● The frozenset class is an immutable form of the set type.


● Sets use curly braces { and } as delimiters for a set.
● Examples:
○ {17}, {‘red’, ‘green’, ‘blue’}
○ {} does not represent an empty set for historical reasons. It
represents an empty dictionary.
○ set() produces an empty set. set(‘hello’) produces {‘h’, ‘e’,
‘l’, ‘l’, ‘o’}.
The dict class
● Represents a dictionary or a mapping, from a set of distinct keys to associated
values.
● A dictionary literal also uses curly braces.

> a = {‘ga’:’Irish’, ‘de’:’German’}

● The literal form { } produces an empty dictionary.

● The constructor for the dict class accepts an existing mapping as a parameter.

● Alternatively, the constructor accepts a sequence of key-value pairs as a parameter, as


in dict(pairs) with pairs:

> b = [( ‘ga’ , ‘Irish’ ), ( ‘de’ , ‘German’ )]


Output
Expressions, Operators & Precedence

● Logical Operator: not, and, or


● Equality Operators: is, is not, ==, !=
● Comparison operators: <, <=, >, >=
● Arithmetic Operators: +, - , *, /, //, %
● Bitwise Operators: ~,&, I, ^, <<, >>
Sequence Operators

● Python relies on zero-indexing of sequences, thus a sequence of length n has elements indexed
from 0 to n − 1 inclusive.

● Python also supports the use of negative indices, which denote a distance from the end of the
sequence; index −1 denotes the last element, index −2 the second to last, and so on.

● Slicing: half-open intervals. Example: data[3:8] denotes a subsequence including the five indices:
3,4,5,6,7.

● All sequences define comparison operations based on lexicographic order, performing an element
by element comparison until the first difference is found. For example, [5, 6, 9] < [5, 7] because of
the entries at index 1
Operators for Sets
Operators for Dictionaries
Extended Assignment Operators
Operator Precedence

● Chained assignment
○ x=y=0
○ 1 <= x + y <= 10
Control Flow: If, While, For, Break & Continue

● A break statement terminates a most immediately closing while or for loop.

● A continue statement causes the current iteration of a loop body to stop, but
with subsequent passes of loop proceeding as expected.
Functions

● The term function is used to describe a traditional, stateless function that is invoked without the
context of a particular class or an instance of that class, such as:
> b = sorted(data)
● The term method is used to describe a member function that is invoked upon a specific object
using an object-oriented message passing syntax, such as:
> c = data.sort()
● The identifiers used to describe the expected parameters are known as formal parameters.

● The objects sent by the caller when invoking the function are the actual parameters.

● Polymorphic functions: more than one possible calling signatures - default parameter values.
Default Parameter: Signature of the function

Valid calls:
Body of the
function
foo(4,12,8)
foo(4)

> def foo (a=10, b=20, c=30):

Positional Argument: End of the function


foo(5) will execute foo(a=5,b=20,c=30)

Keyword Argument:
foo(c=5) will execute foo(a=10,b=20,c=5)

def bar(a, b=5, c) Illegal function signature !!


Input / Output, File I/O
Example 1

● Input from Keyboard: input()


● Output to Console: print()

● File Handling
○ File is a named location on the
disk which is used to store data
permanently.
○ Following operations can be
performed on a file:
■ Open a file
■ Read a file
■ Write a file
■ Close a file

Example 2
Built-in File I/O commands
Exception Handling

● An exception is an event which occurs during the execution of a program that


disrupts its normal flow.

● Exception Handling is the process of dealing with run-time errors and faults
gracefully.

● It includes two major tasks:


○ Throw suitable Exceptions – raise(), assert()
○ Execute suitable functions by catching these exceptions: try … except block
Raise an Exception
Try …. Except block

● A suspicious code can be put in a try: block


and use except: block to handle each kind
of errors that can potentially arise in the
code.
Raise An exception Catch An exception
Assert() Function

● It is used to enforce a condition.

● It raises an exception when the condition is not


met.
Assert Expression[, Arguments]

● if Assertion fails, Python uses ‘Arguments’ for


the AssertionError exception.
Common Exception Types
Iterators & Generators

● An iterator is an object that manages an


iteration through a series of values. ● The most convenient technique for
creating iterators in Python is through the
● If i is an iterator then, each call to the use of generators.
built-in function, next(i), produces a
subsequent element from the underlying ● Generators can have multiple yield
series. commands

● A StopIteration exception raised to ● Iterators and generators provide the


indicate that there are no further elements. benefit of lazy evaluation where the
values are computed if requested, the
● An iterable is an object, obj, that produces entire series need not reside in memory at
an iterator via the syntax: one time.
> i = iter(obj).
Example 1: Generator
Example 2: Generator

Example 3: Iterator by
using iter() command
Additional Python Conveniences
● Conditional Expressions:
● Comprehension Syntax: Produce one series of values based upon the
processing of another series:

○ List Comprehension
● Comprehension Syntax (continued)

● The generator syntax is particularly attractive when results do not need to be stored in memory.

● For example, to compute the sum of the first n squares, the generator syntax, total = sum(k k for
k in range(1, n+1)), is preferred to the use of an explicitly instantiated list comprehension as the
parameter
● Packing and Unpacking of Sequences:
○ Automated Packing: If a series of comma-separated expressions are given in a larger
context, they will be treated as a single tuple, even if no enclosing parentheses are provided.

○ One common use of packing in Python is when returning multiple values from a function

○ Automated Unpacking: Allowing one to assign a series of individual identifiers to the


elements of sequence.

This technique can be used to unpack tuples returned by a function.

This syntax can also be used in the context of a for loop, when iterating over a sequence of
iterables:

Iterate through dictionary items:


● Simultaneous Assignments: Combination of automated packing &
unpacking

Swapping of values:

Example 1

Example 2
Scopes & Namespaces
● The process of determining the value associated with an identifier is known as
name resolution.
● Whenever an identifier is assigned to a value, that definition is made with a
● specific scope.
● Top-level assignments are typically made in what is known as global scope.
● Assignments made within the body of a function typically have scope that is
local to that function call.
● Each distinct scope in Python is represented using an abstraction known as a
namespace.
● First-class objects are instances of a type that can be assigned to an
identifier, passed as a parameter, or returned by a function. In Python,
functions and classes are also treated as first-class objects.
Modules
● A module is a collection of closely related functions and
● classes that are defined together in a single file of source code which could
be imported from within a program.
● Beyond the built-in definitions, the standard Python distribution includes
perhaps tens of thousands of other values, functions, and classes that are
organized in additional libraries, known as modules,

● New modules can be created by putting relevant definitions in a file named


with a .py suffix. Those definitions can be imported from any other .py file
within the same project directory.
Summary
We cover the following topics in this lecture:

● Introduction to Python Programming


● Various Sequence type Classes
● Operators
● Input/Output, file Handling
● Exception Handling
● Iterators & generators
● Python Conveniences
● Namespaces
● Modules

You might also like