Introduction to Python Programming Basics
Introduction to Python Programming Basics
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.
• 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.
• 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:
python [Link]
Icon
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())
OR
Command line
python –m pdb [Link] (debug is the file name)
Checking variable type using
pdb ‘whatis’ command
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
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!
+ concatenates strings.
+= appends strings.
y = x[:] or y=list(x)
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.
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
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).
[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)
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
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
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
120
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.
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
5. String Membership:
We test, if a substring exists within a string or not, using the keyword in.
Methods of Python String
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.
You cannot use backslashes (\) to escape characters inside the expression part of an f-string.