0% found this document useful (0 votes)
43 views279 pages

Python Notes

Uploaded by

vsreeramb
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
43 views279 pages

Python Notes

Uploaded by

vsreeramb
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 279

Module-1

GET Started
1. Knowing The Computer ?
2. What is Python ?
3. Installation
4. Your First Python Program
5. Do's & Don'ts
Module 1, CH 1

Knowing the
Computer
What you will Learn ?
1. Block Diagram of Computer.
2. Memory Hierarchy
3. Principle of Abstraction
4. Language Hierarchy
5. High Level Language ( Compiler & Interpreter )
Block diagram of computer
Basic parts of computer
Central Processing Unit
Input & Output
Input devices are important because they allow
users to enter commands and data.
Examples: Keyboards, mice, scanners, etc.

Output devices are hardware components of a


computer system that are used to show or send
data from the pc to the user or any other device.
Memory
Primary Memory(RAM)
The data and instructions that are currently
being processed are kept in primary memory.

Secondary Memory(ROM)
In contrast to primary memory, secondary
memory is non-volatile, which means that its
contents are not lost when the computer is
turned off.
Memory Hierarchy
Principle of Abstraction
Abstraction is used to hide the internal
functionality of the function from the users.
The users only interact with the basic
implementation of the function, but inner working
is hidden
Language hierarchy
How code executes ?
Interpreter (Python)
What You have Learnt ?
1. Block Diagram of Computer.
2. Memory Hierarchy
3. Principle of Abstraction
4. Language Hierarchy
5. High Level Language ( Compiler & Interpreter )
Module 1, CH 2

What is
Python ?
What is Python ?
Python is a popular programming language
Python is a high-level
Interpreted
Dynamically-typed
Simple
Readable
Versatile
Applications
It is used for:
Web development (server-side),
Software development,
Machine Learning,
So on.....
Why Python ?
Python has a simple syntax.
Easy to learn.
Software Development, Web Development &
Machine Learning(ML).
So many projects can be built.
You can be JOB ready.
What You have Learnt ?

1. What is Python ?
2. Applications
3. Why to learn Python ?
Module 1, CH 3

Installation
Module 1, CH 4

Your First
Python Program
Module 1, CH 5

Do's & Don'ts


Module-2
Flowcharts & Algorithms

1. Flowcharts
2. Algorithms
3. Pseudocode
4. Time & Space Complexity.
Flowcharts
What are Flowcharts ?
Flowchart is a diagrammatic representation of sequence of
logical steps of a program.
Symbols
Flowcharts use simple geometric shapes and arrows for
processes and data flow.
Area of a Rectangle
input:
l,b
Output:
Area of Rectangle
My Approach for getting Idea
Input -> Process -> Output Strategy
Algorithms
Algorithms
Algorithm is a step-by-step procedure, which defines a set
of instructions to be executed in a certain order to get the
desired output.
Sum of 2 digits input:
a,b
step 1 − START
Output:
step 2 − declare three integers a, b,c
Sum of a and b
step 3 − define values of a & b
step 4 − sum calculation of a & b
step 5 − store output of step 4 to c
step 6 − print c
step 7 − STOP
Sum of 2 digits Explaination
input:
a,b
Output:
Sum of a and b
Pseudocode
Pseudocode
A way of expressing an algorithm without conforming
to specific syntax rules.
An informal high-level representation of the actual
code
Example set i to 0
for each i from 0 to 9
if i is odd
print i
end for loop
Time & Space
Complexity
Time Complexity:
The time complexity of an algorithm quantifies the
amount of time taken by an algorithm to run as a function
of the length of the input.

Space Complexity:
Problem-solving using computer requires
memory to hold temporary data or final result
while the program is in execution. The amount
of memory required by the algorithm to solve
given problem
Module-3
Python Introduction
1. Keywords
2. Identifiers
3. Variables, Constants, Literals
4. Datatypes & Type conversions
5. Operators
6. Comments
Keywords
What you will Learn ?

a = 100

int a = 100;
Keywords
Keywords are predefined, reserved words used in Python
programming.

We cannot use a keyword as a variable name, function name,


or any other identifier.
List of Keywords
None and as assert
break continue def del
except for from global
in lambda nonlocal or
raise try while yield
False True async
await class elif
else finally if
import is not
pass return with
Identifiers
Identifiers
Identifiers are the name given to variables, classes, methods, etc.
Variable Identifiers
Method/Function Identifiers
Class Identifiers
Rules
Start with a Letter or Underscore
Followed by Letters, Digits, or Underscores
Avoid Starting with a Digit
No Special Characters(!, @, $, etc.)
Case-Sensitive (e.g: age, Age, and AGE)
Avoid Using Keywords
Valid & Invalid Identifiers

name 3d_model (starts with a digit)


age @result (contains special character)
_count for (a Python keyword)
total_price my-name (contains a hyphen, not allowed)
is_student
calculate_area
student_info
MAX_VALUE
Variables
Variables
In programming, a variable is a container (storage area)
to hold data.
Variables
Rules
Start with a Letter or Underscore
Followed by Letters, Digits, or Underscores
Avoid Starting with a Digit
No Special Characters(!, @, $, etc.)
Case-Sensitive (e.g: age, Age, and AGE)
Avoid Using Keywords
Valid & Invalid Variables

name 3d_model (starts with a digit)


age @result (contains special character)
_count for (a Python keyword)
total_price my-name (contains a hyphen, not allowed)
is_student
calculate_area
student_info
MAX_VALUE
Variables vs Identifiers
Identifiers are names given to entities like variables, functions,
etc., while variables are a specific type of identifier used to store
and manipulate data in a program
Constants
Constants
A constant is a special type of variable whose value cannot be
changed.
Literals
Literals
Literals are representations of fixed values in a program.
They can be numbers, characters, or strings, etc.
Types of Literals
1. Numeric Literals
2. String Literals
3. Boolean Literals
4. None Literal
5. Bytes and Bytearray Literals
6. Raw String Literals
7. Numeric Separator
8. Collection Literals:
- List, Tuple, Set, Dictionary
Data Types
What you will Learn ?
Text Data Type
String
str represents strings of 'hello'
characters, enclosed in single, "world"
double, or triple quotes.e.g: '''hello world'''
Numeric Data Types
int
Represents integer values
(e.g., 1, -10, 100)
float
Represents floating point or decimal values
(e.g., 3.14, -2.5)
complex
complex values (e.g., 3.14j, 1-2i)
Sequence Data Types
Tuple List
ordered ordered
immutable mutable
separated by separated by
commas commas
enclosed in enclosed in
parentheses square brackets
(e.g., (1, 2, 3)). (e.g., [1, 2, 3])
Mapping Data Types
dict
Represents unordered collections of
key-value pairs, enclosed in curly
braces (e.g., {'name': 'John', 'age': 30})..
Set Data Types
set
Represents unordered collections of
unique elements, enclosed in curly
braces (e.g., {1, 2, 3})..
Boolean Data Types
bool
bool represents boolean values, which "True"
can be either True or False. Often used "False"
for logical operations and control flow.
None Data Types
None
Represents a special object that
indicates the absence of a value or a
"null" value.
Type
conversions
Type Conversion
In programming, type conversion is the process of
converting data of one type to another.
For example: converting int data to str.
Type Conversion

Implicit Type Conversion Explicit Type Conversion


Python automatically converts Users convert the data type of
one data type to another. an object to required data type.
Conversion Hierarchy
Built-in type conversion functions
int(): Converts to an integer.
float(): Converts to a floating-point number.
str(): Converts to a string.
bool(): Converts to a boolean.
list(): Converts to a list.
tuple(): Converts to a tuple.
set(): Converts to a set.
dict(): Converts to a dictionary.
Hands on Examples
Value ERROR
Introduction to ASCII Values
The "ASCII value" of a character is a number that
represents that character in the computer's memory.
ord() & chr()
In Python, you can use the ord() function to find the ASCII value
of a character.
Answer
What you have Learnt ?
1. Datatypes
2. Type Conversion
3. ASCII Values
Operators
Arithmetic operators
Assignment Operators

Agenda Comparison Operators


Logical Operators
Topics Covered Bitwise Operators
Special Operators
Arithmetic Operators
+ Addition: Adds two operands.
- Subtraction: Subtracts the right operand
from the left operand.
* Multiplication: Multiplies two operands.
/ Division: Divides the left operand by the
right operand (returns a float).
Arithmetic Operators
Arithmetic Operators
// Floor Division: Divides the left operand by
the right operand and rounds down to the
nearest integer (returns an integer).
% Modulo: Returns the remainder of the
division.
** Exponentiation: Raises the left operand to
the power of the right operand
Arithmetic Operators
Arithmetic Operators Ans
Assignment Operators
= Assignment: Assigns the value on the right
to the variable on the left.
+= Add and Assign: Adds the right operand to
the variable on the left and assigns the result
to the variable.
-= Subtract and Assign: Subtracts the right
operand from the variable on the left and
assigns the result to the variable.
Assignment Operators
Assignment Operators
*= Multiply and Assign: Multiplies the
variable on the left by the right operand and
assigns the result to the variable.
/= Divide and Assign: Divides the variable on
the left by the right operand and assigns the
result to the variable.
//= Floor Divide and Assign: Floor divides the
variable on the left by the right operand and
assigns the result to the variable.
Assignment Operators
Assignment Operators
%= Modulo and Assign: Calculates the
remainder of the division and assigns it to
the variable.
**= Exponentiate and Assign: Raises the
variable on the left to the power of the right
operand and assigns the result to the
variable.
Assignment Operators
Comparision Operators
== Equal to: Checks if two values are equal.
!= Not equal to: Checks if two values are not
equal.
> Greater than: Checks if the left operand is
greater than the right operand.
< Less than: Checks if the left operand is less
than the right operand.
Comparision Operators
Comparision Operators
>= Greater than or equal to: Checks if the left
operand is greater than or equal to the right
operand.
<= Less than or equal to: Checks if the left
operand is less than or equal to the right
operand.
Comparision Operators
Logical Operators
and Logical AND: Returns True if both
conditions are True.
or Logical OR: Returns True if at least one
condition is True.
not Logical NOT: Returns True if the
condition is False, and vice versa.
Logical Operators
Membership Operators
in Membership: Returns True if the value is
present in the sequence.
not in Negated Membership: Returns True if
the value is not present in the sequence.
Membership Operators
Identity Operators
is Identity: Returns True if both variables
point to the same object.
is not Negated Identity: Returns True if the
variables point to different objects.
Identity Operators
Bitwise Operators
Bitwise AND (&): Sets each bit to 1 if both bits
are 1.
Bitwise OR (|): Sets each bit to 1 if at least
one of the bits is 1.
Bitwise XOR (^): Sets each bit to 1 if only one
of the bits is 1.
Bitwise NOT (~): Inverts the bits, changing 1
to 0 and 0 to 1.
Bitwise Operators
Bitwise Operators
Bitwise Left Shift (<<): Shifts the bits to the
left by a specified number of positions.
Bitwise Right Shift (>>): Shifts the bits to the
right by a specified number of positions
Bitwise Operators
Python Operator Precedence
Python Operator Precedence
What you have Learnt ?
1. Arithmetic operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
6. Operator Precedence
Comments
Comments
In computer programming, comments are hints that we use to
make our code more understandable.

Comments are completely ignored by the interpreter.


Types of Comments
Single-line comments
These comments begin with a # symbol and continue until the
end of the line.
Multi-line comments
Docstrings are enclosed in triple quotes (''' or """)
and can span multiple lines.
Input &
Output
Syntax & Indentation
Input
Defnition
"input()" function is used to take input from the user via the
keyboard during the program's execution

Types
input()
int()
float()
Syntax for string Input
String Input
# User input for name (string)
name = input("Please enter your name: ")
Syntax for integer Input
int Input
# User input for age (integer)
age_str = input("How old are you? ")
age = int(age_str) # Convert the input string to an integer

int Input
# User input for age (integer)
age_str = int(input("How old are you? ") )
Syntax for float Input
float Input
# User input for weight (float)
weight_str = input("Enter your weight in kilograms: ")
weight = float(weight_str) # Convert the input string to a float

float Input
# User input for weight (float)
weight_str = float(input("Enter your weight in
kilograms: "))
Input:

Output:
Input:

Output:
Error Handling
Output
Definition
The print() function is used to display output to the console or
terminal. It allows you to show information

*objects
sep
end
file
flush
Example 1: String Input and Output
Expected Input: "John"

Expected Output: "Hello, John!"


Example 2: Integer Input & output
Expected Input: 5

Expected Output: "You entered: 5"


Example 3: Float Input and Output
Expected Input: 3.14

Expected Output: "Value of Pi: 3.14"


Example 4: Taking Multiple Inputs
in a Single Line
Expected Input: 10 20 30

Expected Output: "Sum of Inputs: 60"


Example 5: Specifying Separator in
Output
Expected Input: "John", 25

Expected Output: "Name: John, Age: 25"


Example 6: End Parameter in
Output
Expected Input: 5

Expected Output: "Countdown: 5 4 3 2 1 Blast Off!"


Example 7: Arithmetic Operators

Expected Input: 10, 5

Expected Output:

"Addition: 15, Subtraction: 5,


Multiplication: 50, Division: 2.0"
Example 8: Comparison Operators

Expected Input: 10, 5

Expected Output:

"10 > 5: True, 10 < 5: False,


10 == 5: False, 10 != 5: True"
Example 9: Logical Operators

Expected Input: True, False

Expected Output:

"True and False: False,


True or False: True, not True: False"
Example 10: Taking Yes/No Input
and Handling Case Sensitivity
Expected Input: Yes (or yes, YES, yEs, etc.)

Expected Output: "You entered: Yes"


Example 11: Formatting Output
using f-strings
Expected Input: "Alice", 25

Expected Output: "Name: Alice, Age: 25 years"


Problem
Solving
Topics Covered:
Module 1-5
Finding the Sum of Two Numbers
Sample Input: num1 = 5
num2 = 10

Sample Output: Sum: 15

Topics Covered:
Input and Output, Variables, Arithmetic
Operators.
Finding the Area of a Circle
Sample Input: radius = 5

Sample Output: Area of the circle: 78.53981633974483

Topics Covered:
Input and Output, Variables, Arithmetic
Operators.
Solving Quadratic Equations
Sample Input: a=1
b = -3
c=2

Sample Output: Roots: (2.0, 1.0)

Topics Covered:
Input and Output, Variables, Arithmetic
Operators.
Swap the values of two variables
without using a temporary variable
Sample Input: a = 10
b = 20

Sample Output: After Swapping


a = 20
b = 10
Converting Temperature Units
Sample Input: temperature_celsius = 30

Sample Output: Temperature in Fahrenheit: 86.0


Temperature in Kelvin: 303.15
Topics Covered:
Input and Output, Variables, Arithmetic
Operators.
Basic Currency Converter
Sample Input: amount_in_usd = 100
exchange_rate_usd_to_eur = 0.85

Sample Output: Equivalent amount in EUR: 85.0


Practice
Assignment
Problems
Decision
Making
What is decision making ?
The act or process of deciding something
Based on certain criteria or conditions
Conditional
Statements
Conditional Statements
The most common conditional statements used
for decision-making in programming are
if
if-else
if-elif-else
switch-case
If statement

if

if condition:
# code to be executed if the condition is true
Syntax
The condition is an expression that evaluates to either True or
False. If the condition is true, the indented block of code
under the if statement is executed; otherwise, it is skipped.
if-else Statement

if

el
se
Syntax
If the condition is true, the code block under the if branch is
executed, and the code block under the else branch is skipped.
If the condition is false, the code block under the else branch is
executed, and the code block under the if branch is skipped.

if condition:
# code to be executed if the condition is true
else:
# code to be executed if the condition is false
Example
if-elif-else Statement
if

elif

el
se
if condition1:
# code to be executed if condition1 is true
elif condition2:
# code to be executed if condition2 is true
elif condition3:
# code to be executed if condition3 is true
else:
# code to be executed if none of the conditions are true
Example
Nested if Statements

if
if

els
e

elif

el
se
Example
Simple Calculator Program
(Project)
Create a basic calculator program that
performs addition, subtraction,
multiplication, and division.
Ask the user to enter two numbers and
choose an operation.
Display the result accordingly.
Handle potential errors gracefully.
Strings
What are Strings ?
Data type used to represent textual data.
They are sequences of characters and are enclosed in either
single quotes (' '),
double quotes (" "),
triple quotes (''' ''' or """ """)
How to Create String ?
You can create strings using single, double, or triple quotes.
Triple quotes are used for multiline strings or to include
special characters like line breaks.

single_quoted = 'Hello, world!'


double_quoted = "Hello, world!"
multiline = '''Hello,
world!
Welcome'''
String Indexing
Strings are ordered sequences, and you can access individual
characters using indexing. Python uses zero-based indexing,
where the first character has an index of 0.
String Slicing
2.
3.
String Slicing- Exercise 4.
5.
1. print(s[1]) 6. print(s[2:])
2. print(s[-1]) 7. print(s[:-1])
3. print(s[1:3]) 8. print(s[::2])
4. print(s[1:-1]) 9. print(s[1::2])
5. print(s[:3]) 10. print(s[::-1])

s = 'hello world'
String Slicing- Answers
1. e
2. d
3. el
4. ello worl
5. hel
6. llo world
7. hello worl
8. hlowrd
9. el ol
10. dlrow olleh
String Concatenation
You can concatenate strings using the + operator:
String Concatenation
String Length
You can find the length of a string using the len() function:
String Length
String Methods
Python provides numerous built-in methods for
manipulating strings, such as converting cases, removing
whitespaces, replacing characters, splitting, joining, and more.
String Methods
str.upper()
str.lower()
str.capitalize()
str.title()
str.strip()
str.lstrip()
str.rstrip()
str.startswith(prefix).
str.endswith(suffix)
str.replace(old, new).
String Methods
str.split(separator)
str.join(iterable)
str.find(substring)
str.rfind(substring)
str.index(substring)
str.rindex(substring)
str.count(substring)
str.isalnum()
str.isalpha()
String Methods
str.isdigit()
str.islower()
str.isupper()
str.isspace()
str.isnumeric().
str.isdecimal()
str.startswith(prefix, start, end
str.endswith(suffix, start, end)
String Formatting
Python supports multiple ways of formatting strings,
including old-style % formatting, str.format(), and f-strings
(formatted string literals).
String Formatting
Escape sequences
Special character combinations that are used to represent
characters that are otherwise difficult or impossible to include
directly in a string
Escape sequences
\\: Backslash
\': Single Quote
\": Double Quote
\n: Newline (line break)
\t: Tab
\r: Carriage Return (used for some text file formats)
\b: Backspace (moves the cursor back one space)
\f: Form Feed (used for some text file formats)
\v: Vertical Tab (rarely used)
Problems On
Strings +
Numbers +
Decision Making
Vowel Counter
Write a program that takes a string input from the user and
counts the number of vowels (A, E, I, O, U, and their lowercase
equivalents) in the string.

Sample Input: "Hello, World!"

Sample Output: Number of vowels: 3


Grade Calculator
Create a program that takes the marks of a student in different
subjects as input. Calculate the total marks and average, and
then display the corresponding grade based on the average.

Sample Input: Marks in Math: 85,


Marks in Science: 90,
Marks in English: 78

Sample Output: Total Marks: 253,


Average Marks: 84.33,
Grade: A
Palindrome Checker
Write a program that takes a string input from the user and
checks if it is a palindrome or not. A palindrome is a word,
phrase, number, or sequence of characters that reads the same
backward as forward.

Sample Input: "radar"

Sample Output: It is a palindrome.


Largest of Three Numbers
Write a program that takes three numbers as input and finds
the largest among them using decision-making statements.

Sample Input: Enter three numbers: 15, 8, 21

Sample Output: The largest number is 21.


Leap Year Checker
Write a program that takes a year as input and checks if it is a
leap year or not.
Hint: A leap year is divisible by 4, except for years that are
divisible by 100 but not divisible by 400.

Sample Input: Enter a year: 2024

Sample Output: It is a leap year.


Temperature Converter:
Build a temperature converter program that allows the user to
convert temperatures between Celsius, kelvin and Fahrenheit.

Sample Input: Enter temperature: 32


Enter Units(K or F or C): C
Sample Output:
Temperature in Fahrenheit: 89.6F
Temperature in Kelvin: 305K
Loops
Recap of Decision Making
Decision making helps the computer decide what to do based on
certain conditions.

Condition:
Give chocolate to friend,
if available in Plate

Yayyy, It's Your Birthday


Introducing Loops as
Repeated Decisions:

Now there are 100 Friends.....

Until chocolates are available in


Condition:
the plate, Distribute them
Loops
Loops are used to execute a block of code
repeatedly as long as a certain condition is
true or for a specific number of iterations

Types
while
for
while loop
The while loop executes a block of code as long as a
specified condition is true. It continuously checks the
condition before each iteration and stops when the
condition becomes false.

Syntax:
while condition:
# Code block to be executed repeatedly
while loop
for loop
A for loop is a way to repeat a block of code for each item in a
collection (like a list) or for a specific range of numbers.

Syntax:
for variable in range(start, stop, step):
# Code block to be executed for each variable
for loop
for loop for Sequence
The for loop is used to iterate over a sequence (such as a
list, tuple, string, or dictionary) and execute a block of
code for each item in the sequence.

Syntax:
for item in sequence:
# Code block to be executed for each item
Example:
Nested loops
Nested loops refer to the situation where one
loop is placed inside another loop. This allows
you to execute a set of instructions repeatedly

Syntax:
for outer_var in outer_sequence:
# Code block of the outer loop
for inner_var in inner_sequence:
# Code block of the inner loop
Nested loops
Break
If during the execution of the loop Python
interpreter encounters break, it immediately
stops the loop execution and exits out of it.

Syntax:
while condition:
# Code block inside the loop
if some_condition:
break # Exit the loop if the condition is met
Break
Continue
Continue statement is used to skip the rest
of the current iteration in a loop and move
to the next iteration immediately.

Syntax:
while condition: # Code block inside the loop
if some_condition:
continue #skip this iteration
Continue
Problems On
Loops +
Strings +
Numbers +
Decision Making
Print numbers from 1 to N
Take a positive integer N as input and print all the numbers from
1 to N.
Sample Input: N=5

Sample Output: 1
2
3
4
5
Calculate the sum of N natural numbers
Take a positive integer N as input and calculate the sum of the
first N natural numbers.
Sample Input: N=5

Sample Output: Sum of first 5 natural numbers: 15


Print even numbers from 1 to N
Take a positive integer N as input and print all the even numbers
from 1 to N.
Sample Input: N = 10

Sample Output: 2
4
6
8
10
Print odd numbers from 1 t num
Take a positive integer N as input and print all the odd numbers
from 1 to N.
Sample Input: N = 10

Sample Output: 1
3
5
7
9
Multiplication table of a number
Take a positive integer N as input and print the multiplication
table of N from 1 to 10.
Sample Input: Sample Output:
N=3 Multiplication table of 3:
3x1=3
3x2=6
3x3=9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
Calculate the factorial of a number
Take a positive integer N as input and calculate its factorial (N!).

Sample Input: N=5

Sample Output: Factorial of 5: 120


Functions
Function
Functions are blocks of organised, reusable code that perform
a specific task
Dividing a complex problem into smaller chunks makes our
program easy to understand and reuse.
Types
Declaration/Defining
You define a function using the def keyword, followed
by the function name, parentheses (), and a colon :

Syntax
def function_name(parameters):
# Function body
Function Call
To execute a function and run the code inside it, you call
the function by using its name followed by parentheses ().

Syntax
function_name(arguments)
Parameters and Arguments
Functions can take input values known as parameters or arguments.
Parameters are defined in the function's parentheses during the
function definition.
Arguments are the actual values passed to the function when it is
called.
Return Statement
Functions can return a value using the return
statement. The returned value can be assigned to a
variable or used in expressions.
All at One Place
Positional Arguments
These are the most common type of arguments and are
passed to a function based on their position. The order of the
arguments in the function call must match the order of the
parameters in the function definition.
Keyword Arguments
You can pass arguments to a function using their
names explicitly, known as keyword arguments. This
allows you to pass arguments in any order.
Default Arguments
Default arguments are used to provide default values
for parameters in case no value is passed during the
function call. If no argument is provided for a default
parameter, the default value will be used.
Scope of
Variables
Global Scope
Variables defined outside of any function or block have
a global scope. They can be accessed from anywhere in
the program, including inside functions.
Local Scope
Variables defined inside a function have a local scope.
They are accessible only within the function where they
are defined and not from outside the function.
Recursion
Recusive function
A function that calls itself within its own definition to
solve a problem or perform a task
Recursive function
Base Case: The base case is the condition that specifies
when the function should stop calling itself and return a
result directly. It acts as the stopping criterion for the
recursion, preventing infinite recursion.
Recursive Case: The recursive case is the part
of the function that calls itself with a modified
version of the input, leading to smaller
instances of the same problem.
Recusive function for fibonacci
Recusive function for factorial
Lambda
Lambda function
Is a small, one-line function that can have any number
of arguments but can only have one expression.
Syntax
lambda arguments: expression
Addition of Two Numbers:

Squaring a Number:
Lists
Defnition
A list is a versatile and mutable data structure
used to store a collection of items.
Defined using square brackets []
Contain elements of different data types
Allow duplicates.
Creating Lists
you enclose the elements inside square brackets,
separated by commas.
Accessing Elements
You can access individual elements of a list using
their index. Indexing in Python starts from 0.

Python also supports negative indexing, where -1


refers to the last element
Slicing Lists
You can extract a portion of a list using slicing. Slicing
allows you to create a new list with a subset of elements.
Modifying Elements
You can modify individual elements in a list by accessing
them using their index and then assigning a new value.
Methods
append(): Adds an element to the end of the
list.
insert(): Inserts an element at a specific index.
remove(): Removes the first occurrence of a
specified element.
pop(): Removes and returns the element at a
specified index (or the last element if no index
is given).
index(): Returns the index of the first
occurrence of a specified element.
count(): Returns the number of occurrences of
a specified element in the list.
sort(): Sorts the list in ascending order.
reverse(): Reverses the order of the elements in
the list.
List Concatenation
Lists can be concatenated using the + operator, which
creates a new list containing elements from both lists.
List Comprehensions
List comprehensions provide a concise way to create lists
using a single line of code.

Syntax
new_list = [expression for item in iterable if condition]
Tuple
What is A Tuple ?
Definition
A tuple is an ordered, immutable collection of
elements in Python.
It is similar to a list, but the main difference is
that tuples cannot be changed after creation.
Once a tuple is created, you cannot add,
remove, or modify its elements.
Creating Tuple
To create a tuple, you use parentheses () with elements
separated by commas.

Note: Tuples can also be created without


parentheses, using comma-separated values.
Accessing Values
You can access the values in a dictionary using square
brackets [] with the key.
Methods
Tuples have limited built-in methods due to their immutability.
Some common methods include count() and index().
Indexing
Sets
What is A Set ?
What is A Set ?
Sets in Python are an unordered collection of unique elements
Defined using curly braces {} or the set()
Mutable
Duplicate elements are automatically removed.
Creating Sets
Create a set by enclosing elements within curly
braces {}. Alternatively, you can use the set()
Adding Elements
add() method to add a single element to a set

Removing Elements
remove elements using the remove() or
discard() methods.
Set Operations
Union
Intersection
Difference
Symmetric difference
Set Operations

Union Intersection

Difference Symmetric difference


Set Operations
Set Membership and Length
You can check if an element is present in a set using the in
keyword. The len() function gives the number of elements in
the set.
Frozen Sets
Frozen Sets
A frozenset is an immutable version of a set

Set Comprehensions
Like lists and dictionaries, sets also support
comprehensions for concise set creation.
Set Methods
Some common set methods include clear(), copy(),
pop(), update(), etc.
Dictionary
Defnition
Defnition
A dictionary is an unordered collection of key-value pairs.
Are used to store data in the form of key-value pairs, where
each key is unique.
Creating Dictionaries
To create a dictionary, you use curly braces {} and specify
key-value pairs separated by colons :. Keys and values
can be of any data type.
Creating Dictionaries
Accessing Values
You can access the values in a dictionary using square
brackets [] with the key.
Adding Values
To add new key-value pairs or update existing ones in a
dictionary, you can use square brackets [] and the assignment
operator =.
Modifying Values
You can change the value associated with a key in a
dictionary.
Methods
Dictionaries have several useful methods,
keys()
values()
items()
get()
pop()
update()
Looping
You can use loops to iterate through the keys or values of a
dictionary
Comprehensions
Similar to lists, dictionaries also support comprehensions for
concise dictionary creation
Find the sum of all elements in a
given list of numbers.
Sample Input: [10, 20, 30, 40, 50]

Sample Output: Sum of elements = 150


Find the maximum and minimum
values in a list of numbers.
Sample Input: 15, 2, 7, 25, 10

Sample Output: Maximum = 25,


Minimum = 2
Count the number of occurrences
of a specific element in a list.

Sample Input: [1, 2, 3, 2, 1, 4, 2, 5]


2

Sample Output: Count of 2 = 3


Given two sets, find their intersection
(common elements) and union (all unique
elements combined).

Sample Input: Set A: {1, 2, 3, 4, 5}


Set B: {4, 5, 6, 7, 8}

Sample Output: Intersection: {4, 5}


Union: {1, 2, 3, 4, 5, 6, 7, 8}
Create dictionaries, access values,
update values, and iterate through
key-value pairs.
Sample Input:
my_dict = { 'name': 'John', 'age': 30, 'city': 'New York' }

Sample Output: name : John


age : 31
city : San Francisco

You might also like