0% found this document useful (0 votes)
23 views170 pages

Introduction to Python Programming Basics

Python is a high-level, interpreted programming language known for its simplicity, readability, and ease of use, supporting both structured and object-oriented programming. It features automatic memory management, a broad standard library, and is portable across various platforms. The document also covers debugging techniques, variable types, and operators, emphasizing Python's dynamic typing and ease of learning.

Uploaded by

dimboqsingh
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)
23 views170 pages

Introduction to Python Programming Basics

Python is a high-level, interpreted programming language known for its simplicity, readability, and ease of use, supporting both structured and object-oriented programming. It features automatic memory management, a broad standard library, and is portable across various platforms. The document also covers debugging techniques, variable types, and operators, emphasizing Python's dynamic typing and ease of learning.

Uploaded by

dimboqsingh
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

Introduction to Python Part 1

What is Python?
• Python is a high-level, interpreted programming language designed for
simplicity, readability, and ease of use.
• Python is a language that supports multiple approaches to software design,
principally structured and object-oriented programming.
• It provides automatic memory management and garbage collection
• It is extensible
• It is dynamically typed.
Features of Python
• Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax.
This allows a student to pick up the language quickly.
• Easy-to-read: Python code is more clearly defined and visible to the eyes.

• Easy-to-maintain: Python's source code is fairly easy-to-maintain.

• A broad standard library: Python's bulk of the library is very portable and
crossplatform compatible on UNIX, Windows, and Mac.

• Interactive Mode: Python has support for an interactive mode, which allows
interactive testing and debugging of snippets of code.

• Portable: Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
Features of Python
• Extendable: You can add low-level modules to the Python interpreter. These modules
enable programmers to add or customize their tools to be more efficient.

• Databases: Python provides interfaces to all major commercial databases.

• GUI Programming: Python supports GUI applications that can be created and ported to
many system calls, libraries and windows systems, such as Windows MFC, Macintosh,
and the X Window system of Unix.

• Scalable: Python provides a better structure and support for large programs than shell
scripting.
Some History
 “Over six years ago, in December 1989, I was looking for a "hobby"
programming project that would keep me occupied during the week around
Christmas…I chose Python as a working title for the project, being in a slightly
irreverent mood (and a big fan of Monty Python's Flying Circus).”
–Python creator Guido Van Rossum, from the foreward to Programming Python (1st
ed.)

 Goals:

 An easy and intuitive language just as powerful as major competitors


 Open source, so anyone can contribute to its development
 Code that is as understandable as plain English
 Suitability for everyday tasks, allowing for short development times
“Python is an experiment in how much freedom programmers need. Too much
freedom and nobody can read another's code; too little and expressive-ness is
endangered.”
- Guido van Rossum
Compiled Languages
(ex. C++ or
Fortran)
Interpreted Languages
(ex. Python or
R)
bytecode Python interpreter:
Source code files
Python interpreter follows bytecode
prog.p conversion
y instructions
math.p
y

python [Link]

 Clearly, a lot less work is done to get a program to start running


compared with compiled
languages!
 Bytecodes are an internal representation of the text program that can be
efficiently run by the Python interpreter.
 The interpreter itself is written in C and is a compiled program.
Comparison
Compiled
Interpreted  Longer development
 Easier debugging
 Edit / compile / test cycle is longer!
 Debugging can stop anywhere, swap in
 Harder to debug
new code, more control over state of
 Usually requires a special compilation
program
 (almost always) takes less code to  (almost always) takes more code to get
get things done things done
 Slower programs  Faster
 Sometimes as fast as compiled, rarely  Compiled code runs directly on CPU
faster  Can communicate directly with
 Less control over program behavior hardware
 More control over program behavior
Procedural vs Object Oriented Programming
Types of Programming
Procedural Programming

Concept of Class and Object

Object Oriented Programming


You will interact with Python in both ways

Save file with


extension .py and
execute

Interaction with Python

Execute using Shell


Python example
 The python program (in IDLE) looks like
this:

 The python program (in shell) looks like this:


The Python

Icon

Running Python on the command line:


$ python3

Or
IDE
 An integrated development environment (IDE) is a software
application that helps programmers develop software code
efficiently. It increases developer productivity by combining
capabilities such as software editing, building, testing, and
packaging in an easy-to-use application.
 In Python, it is a coding tool that aids in automating the editing,
compiling, testing, and other steps of an SDLC (software
development lifecycle) while making it simple for developers to
execute, write, and debug code.
Data Types
Expression vs Statement
Python evaluates an expression to get a result (number or other value)
Python executes a statement to perform an action that has an effect (printing something, for example)

Syntax vs Semantic
 What is Python?
 Debugging
Debugging in Python
• Debugging means the process of
finding errors, finding reasons of
errors and techniques of their
fixation.
• An error, also known as a bug, is a
programming code that prevents a
program from its successful
interpretation.
• Errors are of three types –
• Compile Time Error
• Run Time Error
• Logical Error
Errors during debugging
 A syntax error is a bug that occurs when a computer program has an
incorrectly typed statement.
 Semantic errors occur due to the improper use of programming
statements.
 Logic errors occur when programmers misrepresent the step-wise
process or algorithm of a computer program.
 Runtime errors occur due to the computing environment in which the
software code runs.
 A debugger is a tool that can help you pause a program.
 When a program is paused, it’s state is preserved and you can tinker
around and change things as you’d like.
 A debugger is used when:
When your code is broken (didn’t do what you expected it to).
When you want to test a rare condition for an if statement.
When you’re reading someone else's code and want to understand the flow
of execution.
When you want to see the values of your variables at a given moment;
maybe they’re not what you expected them to be.
 Debugging is a four step process:
Discovering the Bug: Is there one? It is not always obvious that you have a bug.
Isolating the Bug: Where is it? Locate the part(s) of the code that is causing the
bug.
Finding the Bug: What exactly is wrong with the buggy code fragment?
Fixing the Bug: How should the buggy fragment be rewritten?
 How to debug the code:
Set breakpoints: Indicate lines of code where the program will pause so you can
examine its state.
Step through code: See how each line of code affects the program's flow.
Inspect values: See how each value changes as the program runs.
Implement a better solution: Cover edge cases and fix the issue.
1. print statement: This is a common debugging
technique which allows us to see values of variables at
different points in the program code. It can help to locate
where and bug is occurring and what is causing it.
2. Debugger: This is another technique which is a tool
allowing us to debug the code line by line and observe the
values of variables at each step. It can help us to
understand how is the code executing and identify the
source of a bug.
3. assert statement: This technique allows us to validate
that certain conditions are true at specific points in the
program code. If an assert statement fails, the program will
stop further executing, allowing to identify the issues or
errors in the code.
4. unit test: This technique is a test which checks a small
piece of code to ensure that it is properly functioning or
not. The unit testing helps us to identify errors early on and
ensures that changes to the code do not make to cause
unintended consequences.
5. version control system: This technique allows us to
track changes to our program code over time. It can help
to identify when a bug was introduced and who was
responsible for it.
pdb Debugger
 The module pdb defines an interactive source code debugger (comes built-in
to the Python standard library) for Python programs. It is actually defined as
the class Pdb which internally makes use of bdb(basic debugger functions)
and cmd (support for line-oriented command interpreters) modules.
 It supports:
setting (conditional) breakpoints,
stepping through code,
source code listing, and
evaluation of arbitrary Python code in the context of any stack frame.
 It also supports post-mortem debugging (the process of analyzing a failed
or crashed application to determine the cause of the failure).
Debugging a Simple Python Adding breakpoints explicitly
program using Python pdb
module
Step1: import pdb,
Step 2: pdb.set_trace() commands
(sets breakpoint line below where we call
set_trace())

line number where our


directory breakpoint is located
path of our file

OR
Command line
python –m pdb [Link] (debug is the file name)
Checking variable type using
pdb ‘whatis’ command

Navigating in pdb prompt


Post-mortem debugging using Python pdb module

pdb supports post-mortem debugging through the pm() and post_mortem() functions.
These functions look for active trace back and start the debugger at the line in the call
stack where the exception occurred.
Checking variables on the Stack Python pdb Breakpoints

We can use args(or use a) to print all the Use the break to display all the
arguments of a function which is currently breakpoints in the program.
active. p command evaluates an
expression given as an argument and
prints the result.

Syntax:
break filename: lineno, condition
Managing Breakpoints

After adding breakpoints with the help of numbers assigned to them, we can manage the
breakpoints using the enable and disable and remove command. disable tells the
debugger not to stop when that breakpoint is reached, while enable turns on the disabled
breakpoints.
Commands:
• b(break): Set breakpoint
• cl(clear): Delete breakpoint
• l(list): list 11 surrounding lines
• p(print): Evaluate and print code on current line
• n(next): “Step Over”
• c(continue): Continue execution, stop at breakpoints
• until: Execute until given line number
• s(step): “Step Into”
• r(return): “Step Out Of”
 What is Python?
 Debugging
 Operators
Operators
 Python supports a wide variety of operators which act like
functions, i.e. they do something and return a value:
 Arithmetic: + - * % **
 Logical: and or /
not
 Comparison: > < >= <= !=

==
 Assignment: =
 Bitwise: & | ~ ^ >>

<<
Short-circuiting in Python refers to the behavior of logical operators and and or where the second
 Identity:
operand
is is not
is not evaluated if the result of the expression can be determined from the first operand
 Membership:
alone. in
It's a form of optimization not in also be used to control program flow.
that can
Try Python as a calculator

 Go to the Python prompt.


 Try out some arithmetic
operators:
% ** == ( )
+
-
*
/
Try Python as a calculator
 Go to the Python prompt.
 Try out some arithmetic
operators: % ** == ()
+ -
Operator Function
*
+ / Addition
- Subtraction
* Multiplication
/ Division (Note: 3 / 4 is 0.75!)
% Remainder (aka modulus)
** Exponentiation
== Equals
More Operators
 Try some comparisons and Boolean operators. True and False
are the keywords indicating those values:
Comments
 # is the Python comment
character. On any line everything
after the # character is ignored by
Python.

 There is no multi-line
comment character as in C
or C++.
 What is Python?
 Debugging
 Operators
 Variables
Variables
 Variables are assigned values using the =
operator
 In the Python console, typing the name of a
variable prints its value
 Not true in a script!

 Variables can be reassigned at any time


 Variable type is not specified
 Types can be changed with a reassignment
Variables cont’d
 Variables refer to a value stored in memory and are created
when first assigned
 Variable names:
 Must begin with a letter (a - z, A - B) or underscore _
 Other characters can be letters, numbers or _
 Are case sensitive: capitalization counts!
 Can be any reasonable length
 Assignment can be done en masse:
x = y = z = 1
Try these
 Multiple assignments can be done on one out!
line:
x, y, z = 1, 2.39, 'cat'
Variable Data Types
 Python determines data types for variables based on the
context

 The type is identified when the program runs, called dynamic


typing
 Compare with compiled languages like C++ or Fortran, where types are
identified by the programmer and by the compiler before the program is
run.

 Run-time typing is very convenient and helps with rapid code


development…but requires the programmer to do more code
testing for reliability.
 The larger the program, the more significant the burden this is!!

Variable Data Types
Available basic types:
 Numbers: Integers and floating point (64-bit)
 Complex numbers: x = x = 3+1j
complex(3,1) or 'dog'
 Strings, using double or single quotes:
"cat"
 Boolean: True and False
 Lists, dictionaries, and tuples
 These hold collections of variables
 Specialty types: files, network connections,
objects
Variable modifying operators
 Some additional arithmetic operators that modify
variable values:
Operator Effect Equivalent to…
x += y Add the value of y to x=x+y
x
x -= y Subtract the value of x =x-y
y
from x
x *= y Multiply the value of x =x*y
x
by y
x /= y Divide the value of x x =x/y
by
y

 The += operator is by far the most commonly used


Check a type
 A built-in function, type(), returns
the type of the data assigned to a
variable.
 It’s unusual to need to use this in a
program, but it’s available if you
need it!

 Try this out in Python – do some


assignments and reassignments
and see what type() returns.
Strings
 Strings are a basic data type in
Python.

 Indicated using pairs of single


'' or double "" quotes.
 Multiline strings use a triple set
of quotes (single or double) to
start and end them.

 Strings have many built-in


functions…
String functions
 In the Python console, create a string
variable called mystr
len(mystr)
 type: dir(mystr)
[Link]()

 Try out some [Link]()


functions:
[Link]()
 Need help?
Try: help([Link]
help([Link])
mal)
The len() function
 The len() function is not a string specific function.

 It’ll return the length of any Python variable that


contains some sort of countable thing.

 In the case of strings it is the number of


characters in the string.
String operators
 Try using the + and += operators with
strings in the Python console.

 + concatenates strings.
 += appends strings.

 Index strings using square brackets, starting


at 0.
String operators
 Changing elements of a string by an index is not
allowed:

 Python strings are immutable, i.e. they can’t be


changed.
String %s means sub
Substitutions in
value
variable name
 Python provides an easy comes after a
way to stick variable %

values into strings called


substitutions
 Syntax for one
variable:

 For more than one:


Variables are listed in
the
substitution order
Variables with operators
 Operators can be
combined freely with
variables and variable
assignment.

 Try some out again!

 This time type them into


the editor.
Click the green triangle
to run the file.
Save the file and it will

The Use of Indentation
Python uses whitespace (spaces or tabs) to define code blocks.
 Code blocks are logical groupings of commands. They are
always
preceded by a colon :
A code block

Another code block

 This is due to an emphasis on code readability.


 Fewer characters to type and easier on the eyes!

 Spaces or tabs can be mixed in a file but not within a code


block.
File vs. Console Code Blocks
 Python knows a code block has  Let’s try this out in Spyder
ended when the indentation is
removed.  This sometimes causes problems
when pasting code into the
 EXCEPT when typing code into console.
the Python console. There an
empty line indicates the end of a 
This issue is something the
code block.
IPython console helps with.
 What is Python?
 Debugging
 Operators
 Variables
 Lists, Tuple, Dictionary (Data types)

Lists
A Python list is a general purpose 1-dimensional container for
variables.
 i.e. it is a row, column, or vector of things
 Lots of things in Python act like lists or use list-style
notation.

 Variables in a list can be of any type at any location, including


other lists.

 Lists can change in size: elements can be added or removed

 Lists are not meant for high performance numerical computing!


 We’ll cover a library for that in Part 2
Making a list and checking it twice…
 Make a list with [ ] brackets.

 Append with the append() function

 Create a list with some initial


elements

 Create a list with N repeated


Try these out yourself!
elements
Edit the file in Spyder and run it.
Add some print() calls to see the
lists.
List functions
 Try dir(list_1)

 Like strings, lists have a number


of
built-in functions

 Let’s try out a few…

 Also try the len() function to see


how many things are in the list:
len(list_1)

Accessing List Elements
Lists are accessed by index.
 All of this applies to accessing strings by index
as well!

 Index #’s start at 0.

 List: x=['a', 'b', 'c',


'd' ,'e']
 First x[0]
element: x[2]
 Nth x[-1]
element: x[-2]
 Last
element:

List Indexing
Elements in a list are accessed by an index
number.

 Index #’s start at 0.

 List: x=['a', 'b', 'c', 'd' ,'e']


 First x[0]  'a'
element:
 Nth element: x[2]  'c'
 Last x[-1] 'e'
element:
 Next-to-last: x[-2] 'd'
List Slicing
 List: x=['a', 'b', 'c', 'd' ,'e']
 Slice syntax: x[start:end:step]
 The start value is inclusive, the end value is exclusive.
 Step is optional and defaults to 1.
 Leaving out the end value means “go to the end”
 Slicing always returns a new list copied from the existing
list
 x[0:1]  ['a']
 x[0:2]  ['a','b']
 x[-3:]  ['c', 'd', 'e'] # Third from the end to the end
 x[2:5:2]  ['c',
'e']
List assignments and deletions
 Lists can have their elements overwritten or deleted (with the del)
command.

 List: x=['a', 'b', 'c', 'd' ,'e']

 x[0] = -3.14  x is now [-3.14, 'b', 'c', 'd', 'e']

 del x[-1]  x is now [-3.14, 'b', 'c', 'd']


More on Lists and Variables
 Open the sample file
list_variables.py
but don’t run it yet!

 What do you think will be


printed?
 Now run it…were you
right?
Variables and Memory Locations
 Variables refer to a value stored in
memory.
 y = x does not mean “make a
copy of the list x and assign it to y”
it means “make a copy of the x
memory location in x and assign it
to y”
y
 x is not the list it’s just a reference
to it.
Copying Lists

 How to copy (2 ways…there are more!):

 y = x[:] or y=list(x)

 In list_variables.py uncomment the code at the bottom and run


it.

 This behavior seems weird at first. It will make more sense


when calling
functions.
Value: Value can be any letter ,number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values
belong to different datatypes.)

Data type: Every value in Python has a data type. It is a set of


values, and the allowable operations on those values.
Numbers:
 Number data type stores Numerical Values.
 This data type is immutable [i.e. values/items cannot be changed].
 Python supports.

Sequence:
 A sequence is an ordered collection of items, indexed by positive integers.
 It is a combination of mutable (value can be changed) and immutable (values cannot be
changed) data types.
 There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples
 Strings:
 A String in Python consists of a series or sequence of
characters - letters, numbers, and special characters.
 Strings are marked by quotes:
 single quotes (' ') Eg, 'This a string in
single quotes'
 double quotes (" ") Eg, "'This a string
in double quotes'"
 triple quotes(""" """) Eg, """This is a paragraph. It is made up of
multiple lines and sentences. """
 Individual character in a string is accessed using a subscript (index).
 Characters can be accessed using indexing and slicing operations
 Strings are immutable i.e. the contents of the string cannot be changed after it is created.
 Indexing in Strings:
 Positive indexing helps
in accessing the string
from the beginning.
 Negative subscript helps
in accessing the string
from the end.
 Subscript 0 or –ve
n(where n is length of
the string) displays the
first element.
Example: A[0] or A[-
5] will display “H”
 Subscript 1 or –ve (n-1)
displays the second
Creating a string >>> s="good morning" Creating the list with elements of
different data types.
Indexing >>> print(s[2])  Accessing the item in
o the position 0
>>> print(s[6])  Accessing the item in
O the
position 2
Slicing( >>> print(s[2:]) - Displaying items from 2nd till
ending
Slice position
operator is od
>>>morning
print(s[:4]) -[Link] items from
-1)
used to Good 1st position till 3rd .
extract
part of a
data type
Concatenation >>>print(s+"friends" -Adding and printing
) good morningfriends the characters of two strings.

Repetition >>>print(s*2) Creates new strings,


good concatenating multiple copies of
morninggood morning the same string
in, not in >>> s="good morning" Using membership operators to
(membership >>>"m" in s check a particular character is in
operator) True string or not. Returns true if
>>> "a" not present.
in s
True
Lists:
List is an ordered sequence of items. Values in the list are called elements / items.
It can be written as a list of comma-separated items (values) between square
brackets[ ].
Items in the lists can be of different data types.

 Operations on list:
 Indexing
 Slicing
 Concatenation
 Repetitions
Creating a list >>>list1=["python", 7.79, Creating the list
101, "hello”] with elements of different
>>>list2=["god",6.78,9] data
types.
Indexing >>>print(list1[0]  Accessing the item in
) python the position 0
>>> list1[2] Accessing the item in
101
the position 2
Slicing( ending >>> print(list1[1:3]) - Displaying items from 1st
position -1) [7.79, 101] till 2nd.
Slice operator is >>>print(list1[1:] - Displaying items from 1st
used to extract ) [7.79, 101, 'hello'] position till last.
part of a string, or
some part of a list
Python
Concatenation >>>print( list1+list2) -Adding and printing
['python', 7.79, 101, 'hello', 'god', the items of two lists.
6.78, 9]
Repetition >>> list2*3 Creates new strings,
['god', 6.78, 9, 'god', 6.78, 9, 'god', concatenating
6.78, 9] multiple copies of the same
string
Updating the list >>> list1[2]=45 Updating the list using index
>>>print( list1) value
[‘python’, 7.79, 45, ‘hello’]
Inserting >>> [Link](2,"program") Inserting an element in 2nd
an element >>> print(list1) position
['python', 7.79, 'program',
45, 'hello']
Removing >>> [Link](45) Removing an element
an element >>> print(list1) by giving the element
['python', 7.79, 'program', 'hello'] directly
 Tuple:
A tuple is same as list, except that the set of elements is enclosed in
parentheses instead of square brackets.
A tuple is an immutable list, i.e. once a tuple has been created, you can't add
elements to a tuple or remove elements from the tuple.
Benefit of Tuple:
• Tuples are faster than lists.
• If the user wants to protect the data from accidental changes, tuple can be used.
• Tuples can be used as keys in dictionaries, while lists can't.
 Basic Operations:
Creating a tuple >>>t=("python", 7.79, 101, Creating the tuple with elements
"hello”) of different data types.
Indexing >>>print(t[0]  Accessing the item in the
) python position 0
>>> t[2] Accessing the item in the
101 position 2 >>> t[0]="a"
Trace back (most recent call last):
Slicing( >>>print(t[1:3])  Displaying items from 1st File "<stdin>", line 1, in <module>
ending position - (7.79, 101) till 2nd. Type Error: 'tuple' object does not support item
1) assignment
Concatenation >>> t+("ram", 67)  Adding tuple elements at
('python', 7.79, 101, 'hello', 'ram', the end of another tuple Altering the tuple data type leads to error.
67) elements
Repetition >>>print(t*2)  Creates new strings,
('python', 7.79, 101, 'hello', concatenating multiple copies of
'python', 7.79, 101, 'hello') the same string
 Mapping:
This data type is unordered and mutable.
Dictionaries fall under Mappings.
 Dictionaries:
Lists are ordered sets of objects, whereas dictionaries are unordered sets.
Dictionary is created by using curly brackets. i,e. {}
Dictionaries are accessed via keys and not via their position.
A dictionary is an associative array (also known as hashes). Any key of the
dictionary is associated (or mapped) to a value.
The values of a dictionary can be any Python data type. So dictionaries are
unordered key-value-pairs(The association of a key and a value is called a key-
value pair )
Dictionaries don't support the sequence operation of the sequence data types
like strings, tuples and lists.
Creating a >>> food = {"ham":"yes", "egg" : Creating the dictionary
"yes", "rate":450 } with elements of
dictionary >>>print(food) different data
{'rate': 450, 'egg': 'yes', types.
'ham': 'yes'}
Indexing >>>> print(food["rate"]) Accessing the item with keys.
450

>>> words = {"house" : "Haus", "cat":"Katze"}


>>> words["car"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'car'
If you try to access a key which doesn't exist, you will get an error message:
Data Compile time Run
type time
int a=10 a=int(input(“enter a”))
float a=10.5 a=float(input(“enter a”))
string a=”panimalar” a=input(“enter a string”)
list a=[20,30,40,50] a=list(input(“enter a list”))
tuple a=(20,30,40,50) a=tuple(input(“enter a tuple”))
 What is Python?
 Debugging
 Operators
 Variables
 Lists, Tuple, Dictionary
 If / Else
If / Else
 If, elif, and else statements are used to
implement conditional program behavior
 Synta if Boolean_value:
x: …some code
elif Boolean_value:
…some other code
else:
…more code

 elif and else are not required – used to chain


together multiple conditional statements or
provide a default case.
If / Else code blocks
 Python knows a code block
has ended when the
indentation is removed.

 Code blocks can be nested


inside others therefore if-elif-
else statements can be
freely nested within others. • Note the lack of “end
if”, “end”, curly
braces, etc.
Indentation of code…easier on the
eyes!
 C:
o
r

 Matla
b: o
r
Shorthand If and If-Else
if a > b: print("a is greater than b")

a = 2
b = 330
print("A") if a > b else print("B")

a = 330
b = 330
print("A") if a > b else print("=") if a ==
b else print("B")
a = 200 Logical
b = 33 AND
c = 500 operator
if a > b and c > a:
print("Both conditions are True")

Logical
a = 33 NOT
b = 200 operator
if not a > b:
print("a is NOT greater than b")

a = 200 Logical OR
b = 33 operator
c = 500
if a > b or a > c:
print("At least one of the conditions is
True")
Match-Case Statement
 Match-case statement is Python's version
of a switch-case found in other languages.
It allows us to match a variable's value
against a set of patterns.
Ternary Conditional Statement
 A ternary conditional statement is a compact way to write an if-else
condition in a single line. It’s sometimes called a "conditional
expression.“
 It is also known as a conditional expression because it evaluates a
condition and returns one value if the condition is True and another if
it is False.
 Syntax: <variable> = <true_value> if <condition> else <false_value>
 What is Python?
 Debugging
 Operators
 Variables
 Lists
 If / Else
 Loops
Iteration
 Repeated execution of a set of statements is called iteration.
 Iteration statements or loop statements allow us to execute a block
of statements repeatedly as long as the condition is true.
 Iterations can exist in three states: Unstarted, Started, and Done.
 It is an object that contains a countable number of values.
 An iterator is an object that can be iterated upon, meaning that you
can traverse through all the values.
 Python Iterators:
__iter__() and __next__()
While Loops
 While loops have a condition
and a code block.
 the indentation indicates what’s in the
while loop.
 The loop runs until the condition is
false.
 The break keyword will stop a
while loop running.
In-loop reference collection
variable for each
collection element

For loops
 for loops are a little different.
The code block
They loop through a collection
of things.
 The for loop syntax has a
collection and
 Each element a code
in the block.
collection is
accessed in
order by a reference variable
 Each element can be used in the code
 The break keyword can be used
block.
in for loops too.
Nested Loops
 A nested loop has one or more loops within the body of another
loop.
 The two loops are referred to as outer loop and inner loop. The outer
loop controls the number of the inner loop's full execution. More than
one inner loop can exist in a nested loop.

A nested loop of for loop looks like A nested loop for while loop looks like
this: this:
break statement with for loop break statement with the while loop

Output
nested loop containing for loops inside it

Output
An infinite loop in Python is a
continuous repetition of the conditional
loop until some external factors like
insufficient CPU memory, error in the
code, etc. occur. It does not have an
explicit end (no loop termination
condition is specified by the
programmer).

Runs infinite times until terminated forcibly.

To avoid this issue, we need to increment the counter so that


the loop will get terminated at a certain specified condition.
Lists with Loops
 A for loop is a convenient way
to process every element in a
list.
 There are several ways for
processing lists’ element-by-
element:
 Loop over the list elements
 Loop over a list of index values and
access the list by index
 Do both at the same time
 Use a shorthand syntax called a
list comprehension
 List comprehension is a part of functional programming which
provides a crisp way to create lists without writing a for loop.

[i**3 for i in [1,2,3,4] if i>2] means take item one by one from list [1,2,3,4] iteratively and then check if it is
greater than 2. If yes, it takes cube of it. Otherwise ignore the value if it is less than or equal to 2. Later it
creates a list of cube of values 3 and 4. Output : [27, 64]
The range() function
 The range() function auto-generates sequences of numbers
that can be used for indexing into lists.
Syntax: range(start, exclusive end, increment)

 If you do need to iterate over a sequence of numbers, the


built-in function range() comes in handy. It generates
arithmetic progressions.
Eg: # Prints out the numbers 0,1,2,3,4
for x in range(5):
print(x)
The range() function
range(0,4)  produces the sequence of numbers 0,1,2,3
range(-3,15,3)  -3,0,3,6,9,12
range(4,-3,-2)  4,2,0,-2

 Try this: print(range(4))

This function does not store all the values in memory, it would be inefficient. So it remembers
the start, stop, step size and generates the next number on the go.
For-Else and While-Else
 In a for or while loop the break statement
may be paired with an else clause. If the
loop finishes without executing the break,
the else clause executes.
 In a for loop, the else clause is executed
after the loop finishes its final iteration,
that is, if no break occurred.
 In a while loop, it’s executed after the
loop’s condition becomes false.
• `For-else` loop is used with
iterables (sequences), while
`while-else` loop is used with
a conditional statement.
• `For-else` loop executes the
`else` block when the entire
sequence is iterated, whereas
`while-else` loop executes the
`else` block when the
condition becomes false.
 What is Python?
 Debugging
 Operators
 Variables
 Lists
 If / Else
 Loops
 Unconditional Statement
 Unconditional Statement
A situation in which need to exit a loop completely when an external condition
is triggered or need to skip a part of the loop. In such a situation python provide
unconditional statements.
 Types of Unconditional looping Statement
1. break statement
2. continue statement
3. pass statement
1. break statement
 A break statement terminates the current loop and transfers the
execution to statement immediately following the loop. The break
statement is used when some external condition is triggered.

2. continue statement
 A continue statement returns the control to the beginning of the loop
statement. The continue statement rejects all remaining statement
and moves back to the top of the loop.
3. pass statement
 A pass statement is a null operation, and nothing happens when it
executed. It can be used when a statement is required syntactically
but the program requires no action.
Break
Output

Differences Between Pass and Continue in Python


Pass and continue statements are not interchangeable in Python. A pass statement
signals to a loop that there is “no code to execute here.” It’s a placeholder for future
code. A continue statement is used to force the loop to skip the remaining code and
start the next iteration.
 What is Python?
 Operators
 Variables
 Lists
 If / Else
 Loops
 Unconditional Statement
 Functions
Functions
 Function is a sub program which consists of set of instructions used to perform a
specific task.
 A large program is divided into basic building blocks called function.
 A function is a block of organized, reusable code that is used to perform a single,
related action.
 Functions provide better modularity for your application and a high degree of code
reusing.
 Functions can be classified into two categories:
1. Built in function
2. User defined function Additional in Python
3. Lambda function
4. Recursive function
 Need For Function:
When the program is too complex and large they are divided into parts. Each
part is separately coded and combined into single program. Each subprogram is
called as function.
Debugging, Testing and maintenance becomes easy when the program is
divided into subprograms.
Functions are used to avoid rewriting same code again and again in a program.
Function provides code re-usability
The length of the program is reduced.
1. Built in functions:
Built in functions are the functions that are already created and stored in python.
These built in functions are always available for usage and accessed by a programmer. It
cannot be modified.
2. User defined functions:
User defined functions are the functions that programmers create for their requirement
and use.
These functions can then be combined to form module which can be used in other
programs by importing them.
Advantages of user defined functions:
• Programmers working on large project can divide the workload by making different functions.
• If repeated code occurs in a program, function can be used to include those codes and execute when
needed by calling that function.
3. Lambda functions:
Functions which are small and that can take any number of arguments but can only
have one expression.
Anonymous functions, which are also called lambda functions because they are not
declared with the standard def keyword.
Lambda functions are often used for quick, simple operations that don’t require a full
function definition.
4. Recursive functions:
Functions that can call themselves again and again from their own body.
These are functions that take other functions as arguments and/or return functions
as output. Higher-order functions can be used to create more complex operations by
combining simpler functions.

A method refers to a function which is part of a class. You access it with an instance or object
of the class.
User defined Lambda Recursive
def greet(name): double = lambda x: x * 2 def factorial(n):
print(“Hello, “ + name + “!”) if n == 0:
print(double(5)) return 1
greet(“friend”) else:
return n * factorial(n-1)

print(factorial(5))
Output: Output: Output:
Hello, friend! 10 120
Function Syntax in Python

 You need to use the def keyword, give your function a name, followed by a pair of
parentheses, and end the line with a colon (:).
 If your function takes arguments, the names of the arguments (parameters) are
mentioned inside the opening and closing parentheses.

Please note that in function definition, the arguments that your function consumes are
referred to as parameters.
 When you call the function with specific values for these parameters, they're
called arguments or actual parameters. This is because the arguments in the
function call are the values used for the function's parameters.
 Then, you begin an indented block. This is the body of the function that
describes what your function does.
 There's a return statement that returns the result of the operation on the
arguments. The return statement returns control to the point where the
function was originally called.

Note that the arguments and the return statement are optional. This means that
you could have a function that takes in no arguments, and returns nothing.
Examples of function without and with arguments

Function definition

Function call
The arguments in the function
call are positional arguments.

keyword arguments
#Output

• Positional parameters: Arguments are passed in the same


order they are defined.
default arguments
• Keyword parameters: Arguments are passed with the
parameter name, regardless of the order.

• Default parameters: Python allows function arguments to


have default values. If the function is called without the
argument, the argument gets its default value.
Special Parameters in Python

Positional-Only Parameters (/):


Parameters defined before the / symbol can only be passed by position, not by name.

Keyword-Only Parameters (*):


The parameters defined after the * can only be passed using their names.

Python does not support function


overloading.
When we define multiple functions
with the same name, the later one
always overrides the prior.
Variable Length Arguments/Arbitrary Arguments
(Packing and Unpacking of function arguments)

 Packing refers to collecting multiple values into a single data structure (like a list or
tuple).
 Unpacking is the process of extracting values from a collection and assigning them to
variables.
 During function call, we can unpack python list/tuple/range/dictionary and pass it as
separate arguments.
* is used for unpacking positional arguments.
** is used for unpacking keyword arguments.

Unpacking function arguments are used when we want to unpack list/tuple/dict during the
function call.
Packing function arguments are used when we don’t want the number of parameters passed
during the function call. The same function can be used for the different number of
parameters.
Two forms of packing and unpacking
in function’s arguments

positional arguments keyword arguments


*args (or “variable-length positional **kwargs (or “variable-length keyword
arguments/Arbitrary Positional Arguments”) arguments/Arbitrary Keyword Arguments”)
This syntax allows a function to receive any This syntax allows a function to receive any
number of positional arguments. The arguments number of keyword arguments. The arguments are
are passed to the function as a tuple. passed to the function as a dictionary.
Unpacking positional arguments

When the arguments are in the


form of sequences like
list/tuple/range, we can unpack
them during the function call
using the * operator.

Packing positional arguments

Sometimes during the function call, we


may use an arbitrary number of
arguments. Since we don’t know the
number of arguments to be passed
during the function call, we can use
packing to pack all the arguments in a
tuple.
Unpacking positional arguments

Example 1: Unpacking positional Example 3: TypeError raised when the


arguments during the function call. number of parameters doesn’t match

mul(*num )→ It will unpack the elements in the list and will


assign them to the parameters mentioned in the function
definition in the same order.
1→a
2 →b
Example 4: If we just mention the list name
3 →c during the function call, it will raise an error.

Example 2: Checking how the unpacking is


done.
Packing positional arguments

Example 1: Passing an arbitrary number Example 2: Before the variable number of


of arguments during the function call. arguments, zero or more normal arguments can
occur.

120

Error if normal argument is passed as keyword


argument before variable number of arguments
Packing positional arguments
Example 3: Error is raised when normal
parameters appear after the variable number of
arguments.
Unpacking keyword arguments
When the arguments are in the form of
a dictionary, we can unpack them
during the function call using the **
operator.
A double asterisk ** is used for
unpacking a dictionary and passing it
as keyword arguments during the
function call.

Packing keyword arguments Keyword arguments: keyword


arguments are in the
form kwargs=value
Sometimes during the function call, we
may use an arbitrary number of
keyword arguments. Since we don’t
know the number of keyword
arguments to be passed during the
function call, we can use packing to
pack all the keyword arguments in a
dictionary.
Unpacking/Packing keyword arguments

Example 1: Unpacking dictionary during the Example 1: Passing an arbitrary number of


function call. keyword arguments during the function call.
mul(**d )→ It will unpack the elements in the dictionary and pass it The same function can be used for different numbers of
as keyword arguments during the function call. parameters.
a=4
b=5
c=7

kwargs will store keyword


arguments in form of dictionary.
 Call by value and call by reference
Call by Value
It is a way of passing arguments to a function in which the arguments get copied to
the formal parameters of a function and are stored in different memory locations. In short,
any changes made within the function are not reflected in the actual parameters of the
function when called.
Call by Reference
It is a way of passing arguments to a function call in which both the actual argument
and formal parameters refer to the same memory locations, and any changes made within
the function are reflected in the actual parameters of the function when called.

Python variables are not storage containers. Rather Python’s variables


are like memory references. They refer to the memory address where
the value is stored.
 Python programming language uses the mechanism of the call-by-object and
also call by object reference.

 Each object whenever it is instantiated, it is assigned unique id and its type if


defined at runtime and id(object) returns a unique identity (integer value) of that
object.

 When Mutable objects are passed to the function call then it is treated as call by
value and when Immutable objects are passed to the function call and there value
is modified then it is treated as call by reference.

 For the sake of simplicity we use the word call by value and call by reference
instead of call by object and call by object reference, respectively.
Output
Output
Output
Output
Fruitful Function
 A function that returns a value, which can be used in other parts of a
program is a fruitful function.
 Functions that return values are sometimes called fruitful functions while a
function that doesn't return a value can be simply called a function.

The return statement is followed by an expression which is


evaluated. Its result is returned to the caller as the “fruit” of
calling this function.
Returning a Single Value

Assigning and Using the Return Value

Returning Multiple Values

assigns in form of tuple


 Dead Code
Dead code in Python refers to lines or blocks of code that exist in
a program but are never executed. It's like having a dusty old book on
your shelf that you've never opened.

In this example,
the calculate_cube func
tion is dead code
because it is never
called by
the main function.
 Void Functions
Void functions, as the name implies, do not return anything. They do a series
of activities and run commands without creating any results. These functions
are critical for code modularization, reusability, and improved code
organization.
Fruitful functions, on the other hand, are intended to return a value and
provide the caller with information.
 Function Composition
Function composition in productive functions is a powerful Python programming
technique that enables you to combine many functions to build more complicated
and reusable code. It's like building blocks for your code, with each function
performing a specific task that can be effortlessly integrated to get the required result.
Using function composition makes your code more modular and easier to maintain.
You can reuse existing functions to increase code reusability and efficiency in your
programs. This method improves code readability and promotes a clean, organized
coding style.
 Local and Global Scope
Local scope refers to variables defined within
a given function. These variables are specific
to that function, providing encapsulation and
limiting unintentional interaction with other
portions of your program. Global scope, on
the other hand, refers to variables that are
declared outside of any function and hence
available across the codebase.
In the context of fruitful functions, local scope
becomes pivotal. Variables specified within
the function are only valid during its
execution, ensuring a controlled computing
environment. When a variable is required
outside of the bounds of a given function,
global scope is invoked, allowing it to be used
across the program.
 Nonlocal scope
In Python, a nonlocal scope
is a variable defined in an
outer function that can be
accessed and modified from
an inner function. The
nonlocal keyword is used to
create nonlocal variables.
Nonlocal variables are useful
for sharing data between
nested functions.
With nonlocal keyword Without nonlocal keyword
Global variable
Local variable
Use of global keyword for local variable

The keyword "global" is used to indicate that a variable is a global variable, as opposed to a
local variable. This means that the variable can be accessed and modified from anywhere in
the code, rather than just within the scope of the function or block in which it is defined.
Recursion
 Any function that calls itself in its body repeatedly until a particular
condition becomes false and the target task is done is called a
"Recursive function" and this procedure is called “Recursion”.

 It is always made up of 2 portions, the base case and the recursive case.
The base case is the condition to stop the recursion.
The recursive case is the part where the function calls on itself.
 Advantages of Recursion
i. Recursive functions make the code look clean and elegant.
ii. A complex task can be broken down into simpler sub-problems using
recursion.
iii. Sequence generation is easier with recursion than using some nested
iteration.
 Disadvantages of Recursion
i. Sometimes the logic behind recursion is hard to follow through.
ii. Recursive calls are expensive (inefficient) as they take up a lot of memory
and time.
iii. Recursive functions are hard to debug.
Recursion Example-1 Recursion Example-2

Output: 24

Output: 21
 What is Python?
 Operators
 Variables
 Lists
 If / Else
 Loops
 Unconditional Statement
 Functions
 Strings (Revisited)
Strings (Revisited)
 A String in Python consists of a series or sequence of characters - letters, numbers, and special
characters.
 Strings are marked by quotes:
 single quotes (' ') Eg, 'This a string in single quotes'
 double quotes (" ") Eg, "'This a string in double quotes'"
 triple quotes(""" """) Eg, """This is a paragraph. It is made up of multiple lines
and sentences. ""“
 Positive indexing helps in accessing the string from the beginning.
 Negative subscript helps in accessing the string from the end.
 Operations on string:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Membership
Positive Indexing

Negative Indexing

Slicing

If we try to access an index out of the range


or use numbers other than an integer, we
will get errors.
Python String Operations
1. Compare Two Strings:
We use the == operator to compare two strings. If two strings are
equal, the operator returns True. Otherwise, it returns False.
2. Join Two or More Strings:
In Python, we use the + operator to join (concatenate) two or more
strings.

3. Iterate through a Python String:


We can iterate through a string using a for loop.
4. Python String Length:
In Python, we use the len() method to find the length of a string.

5. String Membership:
We test, if a substring exists within a string or not, using the keyword in.
Methods of Python String

Chaining String methods

The strip() method removes any leading, and


trailing whitespaces.
String join method String slice method
Syntax: Syntax:
[Link](iterable) slice(start, end, step)

String split method


Syntax:
[Link](separator, maxsplit)
Escape Sequences in Python
 The escape sequence is used to escape some of the characters
present inside a string.
Example:
Suppose we need to include both a double quote and a single quote inside a string:
throws error

To solve this issue, we use the escape character \ (backslash) in Python.


 Raw strings treat backslashes as literal characters and are created by
prefixing the string with an r or R. This is particularly useful for regular
expressions and file paths.

In addition to using triple quotes for multi-line strings, you can use
the backslash (\) to continue a string onto the next line without
including a newline character.
 raw_input : Reads a string of text from user input.

Raw input
Python String Formatting (f-Strings)
 Python f-Strings (formatted string literals) makes it easy to print values and variables.
 f (formatted) in string allows you to format selected parts of a string.
 To format values in an f-string, add placeholders {}, a placeholder can
contain variables, operations, functions, and modifiers to format the
value.

 A placeholder can also include a modifier to format the value.


 A modifier is included by adding a colon : followed by a legal
formatting type, like .2f which means fixed point number with 2
decimals:

You cannot use backslashes (\) to escape characters inside the expression part of an f-string.

You might also like