Python Notes
Python Notes
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.
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
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.
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:
Expected Output:
Expected Output:
Topics Covered:
Input and Output, Variables, Arithmetic
Operators.
Finding the Area of a Circle
Sample Input: radius = 5
Topics Covered:
Input and Output, Variables, Arithmetic
Operators.
Solving Quadratic Equations
Sample Input: a=1
b = -3
c=2
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
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.
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.
Condition:
Give chocolate to friend,
if available in Plate
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: 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!).
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.
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.
Removing Elements
remove elements using the remove() or
discard() methods.
Set Operations
Union
Intersection
Difference
Symmetric difference
Set Operations
Union Intersection
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]