Python Tutorial Full Notes - Rishabh Mishra (1)
Python Tutorial Full Notes - Rishabh Mishra (1)
Python for
Beginners
Notes by Rishabh
Mishra
Chapter - 01
Introduction to Python
What is programming
What is Python
Popular programming languages
Why Python
Career with Python
What is Python?
Python is a high-level programming language known for its simplicity
and readability.
Just like we use Hindi language to communicate and express ourselves,
Python is a language for computers to understand our instructions &
perform tasks.
Note: Python was created by Guido van Rossum in 1991.
Why Python?
Python is one of the easiest programming languages to learn and
known for its versatility and user-friendly syntax, is a top choice among
programmers.
Also, python is an open source (free) programming language and have
extensive libraries to make programming easy. Python has massive
use across different industries with excellent job opportunities.
In above examples we can see that Python is simple in writing & reading the
code.
Chapter - 02
Python Installation & Setup + Visual Studio Code Installation
Python installation
Visual Studio Code installation
Install Python
Step 1: Go to website:
https://www.python.org/downloads/ Step 2: Click on
“Download Python” button
(Download the latest version for Windows or macOS or Linux
or other) Step 3: Run Executable Installer
Step 4: Add Python to Path
Step 5: Verify Python Was Installed on Windows
Open the command prompt and run the following command:
python --version
Chapter - 03
Python As a Calculator
Python can be used as a powerful calculator for performing a wide
range of arithmetic operations.
2+5 add two
numbers print(10/5) divide
two numbers
Python Syntax
Interpreter Compiler
An interpreter translates and A compiler translates the entire
executes a source code line by code into machine code before
line as the code runs. the program runs.
Chapter - 04
Variables in Python
What is a Variable
Variables - examples
Variable Naming Rules
Variables in Python
A variable in Python is a symbolic name that is a reference or pointer to
an object.
In simple terms, variables are like containers that you can fill in with
different types of data values. Once a variable is assigned a value, you
can use that variable in place of the value.
We assign value to a variable using the assignment operator (=).
Syntax: variable_name =
value Example: greeting =
"Hello World"
print(greeting)
Variable Examples
Python can be used as a powerful calculator for performing a wide
range of arithmetic operations.
flythonLev = "Beginner pascal
el " case
pythonLev = "Beginner camel
el " case
pythonlev = "Beginner flat
el " case
python_lev = "Beginner Snake
P y thon No te s by Ris habh Mish
ra
el " case
a, b, c = 1, 2, 3
print(a, b, c) assign multiple variables
_my_name =
"Madhav" ⬛ for =
26 +
‘for’ is a reserved word in flython
Chapter - 05
Chapter - 06
Type Casting
Type casting in Python refers to the process of converting a value from
one data type to another. This can be useful in various situations, such as
when you need to perform operations between different types or when
you need to format data in a specific way. Also known as data type
conversion.
Python has several built-in functions for type casting:
int(): Converts a value to an integer.
float(): Converts a value to a floating-point
number. str(): Converts a value to a string.
list(), tuple(), set(), dict() and bool()
Types of Typecasting
There are two types of type casting in python:
Implicit type casting
Explicit type casting
Converting String to
Converting a value to
boolean: bool(0) Output:
False
bool(1) Output: True
Chapter - 07
num1 =
int(num1) num2
= int(num2)
Calculating the sum and display the result
Chapter - 08
Operators in Python
What are Operators
Types of Operators
Operators Examples
Operators in Python
Operators in Python are special symbols or keywords used to perform
operations on operands (variables and values).
Operators: These are the special symbols/keywords. Eg: + , * , /, etc.
Operand: It is the value on which the operator is applied.
Examples
Addition operator a + b
'+':
Equal operator a == b
'==':
and operator 'and': a > 10 and b <
20
Types of Operators
Python supports various types of operators, which can be broadly
categorized as:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Identity Operators
P y thon No te s by Ris habh Mish
ra
7. Membership Operators
Operator Description
() Parentheses
** Exponentiation
+, -, ~ Positive, Negative, Bitwise NOT
*, /, //, % Multiplication, Division, Floor Division,
Modulus
+, - Addition, Subtraction
==, !=, >, >=, <, <= Comparison operators
is, is not, in, not in Identity, Membership Operators
NOT, AND, OR Logical NOT, Logical AND, Logical OR
<<, >> Bitwise Left Shift, Bitwise Right Shift
&, ^, | Bitwise AND, Bitwise XOR, Bitwise OR
1.Arithmetic Operators
Arithmetic operators are used with numeric values to perform
mathematical operations such as addition, subtraction, multiplication,
and division.
3.Assignment Operators
Assignment operators are used to assign values to variables.
6.Bitwise Operators
Bitwise operators perform operations on binary numbers.
Chapter - 09
Example:
age = 26
if age > 19:
print("You are an adult")
Syntax:
if condition:
Code to execute if the condition is true
else:
Code to execute if the condition is false
Example:
temperature = 30
if temperature > 25:
print("It's a hot
day.")
else:
print("It's a cool day.")
Syntax:
if condition1:
Code to execute if condition1 is true
elif condition2:
Code to execute if condition2 is true
else:
Code to execute if none of the above conditions are
true
Example:
Grading system: Let’s write a code to classify the student’s grade based
on their total marks (out of hundred).
score = 85
if score >= 90:
print("Grade - A")
elif score >= 80:
print("Grade - B")
elif score >= 70:
print("Grade - C")
else:
print("Grade - D")
Example:
Number Classification: Let's say you want to classify a number as
positive, negative, or zero and further classify positive numbers as
even or odd.
number = 10
if number > 0: First check ifi the number is positive
if number % 2 == 0:
print("The number is positive and
even.") else:
print("The number is positive and
odd.") else: The number is not positive
if number == 0:
print("The number is
zero.") else:
print("The number is negative.")
5.Conditional Expressions
Conditional expressions provide a shorthand way to write simple if-else
statements. Also known as Ternary Operator.
P y thon No te s by Ris habh Mish
ra
Syntax:
value_if_true if condition else value_if_false
Example:
age = 16
status = "Adult" if age >= 18 else
"Minor" print(status)
Conditional Statements- HW
Q1: what is expected output and reason?
value = one
if value:
print("Value is True")
else:
print("Value is False")
Chapter - 10
Functions in Python
Functions definition
Types of Functions
Function examples
Functions in Python
A function is a block of code that performs a specific task. You can use it
whenever you want by calling its name, which saves you from writing
the same code multiple times.
Benefits of Using Function: Increases code Readability & Reusability.
Basic Concepts:
• Create function: Use the def keyword to define a function.
• Call function: Use the function's name followed by () to run it.
• Parameter: The variable listed inside parentheses in function definition.
• Argument: The actual value you pass to function when you call it.
Types of Functions
Below are the two types of functions in Python:
1. Built-in library function:
• These are Standard functions in Python that are available to use.
• Examples: print(), input(), type(), sum(), max(), etc
2. User-defined function:
• We can create our own functions based on our requirements.
• Examples: create your own function :)
# return result is optional, Use if you want the function to give back a value
Output: 8
value
Calling this fiunction to return a
temp_f = celsius_to_fahrenheit(25)
print("Temperature in Fahrenheit:", temp_f)
Functions – HW
Write a Python program to create a calculator that can perform at least five
different mathematical operations such as addition, subtraction,
multiplication, division and average. Ensure that the program is user-
friendly, prompting for input and displaying the results clearly.
Chapter - 11
Arguments in Function
Arguments are the values that are passed into a function when it’s
called. A function must be called with the right number of arguments. If
a function has 2 parameters, you must provide 2 arguments when
calling it.
Default Arguments
You can assign default values to arguments in a function definition. If a value isn't
provided when the function is called, the default value is used.
Example: function defined using one parameter & default value
Keyword Arguments
When calling a function, you can specify arguments by the parameter name. These are
called keyword arguments and can be given in any order.
Example: function defined using two parameters
def
add_numbers(*args)
: return sum(args)
Note: Here, *args collects all the passed arguments into a tuple, & sum() function adds them.
Example 2:
def
greetings(*name
s): for name in
names:
print(f"Hello, {name}!")
greetings("Madhav", "Rishabh",
"Visakha") Output:
Hello, Madhav!
Hello, Rishabh!
Hello, Visakha!
Output:
name:
Madhav
age: 26
city: Delhi
Example 2:
def
shopping_cart(**products):
total = 0
print("Items flurchased:")
for item, price in products.items():
print(f"{item}: ₹{price}")
total += price
print(f"Total: ₹{total}")
Output:
Items
flurchased:
apple: ₹15
orange: ₹12
mango: ₹10
Total: ₹37
Chapter - 12
Strings in Python
A string is a sequence of characters. In Python, strings are enclosed within single (') or
double (") or triple (""") quotation marks.
Examples:
Example:
name = "Madhav"
age = 16
print("My name is %s and I’m %d." % (name, age))
%s, %d are placeholders fior strings and integers
Example:
name = "Madhav"
age = 16
print("Mynameis {} and I’m {}.".format(name, age))
You can alsorefierence the variables by index or
keyword:
print("Mynameis {0} and I’m {1}.".format(name, age))
print("Mynameis {name} and I’m
{age}.".format(name="Madhav",
age=28))
Example:
name =
"Madhav" age =
16
print(f"My name is {name} and I’m {age}.")
You can also perfiorm expressions inside the
placeholders:
print(f"In 5 years, I will be {age + 5} years old.")
Escape Characters
Escape characters in Python are special characters used in strings to represent
whitespace, symbols, or control characters that would otherwise be difficult to include.
An escape character is a backslash \ followed by the character you want to insert.
Examples:
Chapter - 13
String Indexing
You can access individual characters in a string using their index. Python uses zero-based
indexing, meaning the first character has an index of 0. Index: Position of the character.
Syntax:
string[Index_Value]
Example:
name = "MADHAV"
String Slicing
Slicing in Python is a feature that enables accessing parts of the sequence. String slicing
allows you to get subset of characters from a string using a specified range of indices.
Syntax:
string[start : end : step]
Example:
name = "MADHAV"
name[0:2] = 'MA'
name[0:5:2] = 'MDA'
Example:
name = "MADHAV"
String Methods
Chapter - 14
Loops in Python
• Loops & Types
• While Loop
• For Loop
• Range Function
• Loop Control Statements
Loops in Python
Loops enable you to perform repetitive tasks efficiently without writing redundant code. They
iterate over a sequence (like a list, tuple, string, or range) or execute a block of code as long as
a specific condition is met.
While Loop
The while loop repeatedly executes a block of code as long as a given condition remains
True. It checks the condition before each iteration.
Syntax:
while condition:
Code block to execute
Example: Print numbers firom 0 to 3
count = 0
while count < 4: Condition
print(count
) count +=
1
Output: 0 1 2 3
For Loop
The for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary,
set, or string) and execute a block of code for each element in that sequence.
Syntax:
for variable in sequence:
Code block to execute
Example: iterate over each character in language
lat:ua:v = 'flQtkot’
for x in language:
print(x) Output: P y t h o n
Exampl
e: for i in range(3):
print(i)
else:
print("Loop completed")
Output: 0 1 2 Loop Completed
for loop
• A for loop iterates over a sequence (like a strings, list, tuple, or range)
and runs the loop for each item in that sequence.
• It is used when you know in advance how many times you want to repeat
a block of code.
• pass statement
• break Statement
• continue Statement
Exampl
e: for i in range(5):
code to be updated
pass
Above example, the loop executes without error using pass statement
Exampl
e: for i in range(5):
if i == 3:
break
print(i) Output: 0 1 2
Above example, the loop terminated when condition met true for i == 3
Exampl
e: for i in range(5):
if i == 3:
continue
print(i) Output: 0 1 2 4
Above example, the loop skips when condition met true for i == 3
Output: 5 4 2 1
Output: 5 4 3 3…….
P y thon No te s by Ris habh Mish
ra
Validate User Input
validate user input: controlled infiinite while loop using
break statement
while True:
user_input = input("Enter 'exit' to STOfl: ")
if user_input == 'exit':
print("congarts! You guessed it right!")
break
print("sorry, you entered: ", user_input)
Chapter - 15
Syntax:
Outer_loop:
inner_loop:
Code block to execute - innsr
loop Code block to execute - outsr
loop
i = 1
while i < 4: Outer while loop (runs 3 times)
for j in range(1, 4):
print(j)
print()
i += 1
Chapter - 16
List in Python
• What is List
• Create Lists
• Access List: Indexing & Slicing
• Modify List
• List Methods
• Join Lists
• List Comprehensions
• Lists Iteration
List in Python
A list in Python is a collection of items (elements) that are ordered, changeable
(mutable), and allow duplicate elements.
Lists are one of the most versatile data structures in Python and are used to store
multiple items in a single variable.
Example:
fruits = ["apple", "orange", "cherry", "apple"]
print(fruits)
Output: ['apple', 'orange', 'cherry', 'apple']
Syntax list_name[index
: ]
Exampl
e:
fruits ["apple", "cherry", "apple",
= "orange", "mango"]
List Slicing
Slicing allows you to access a range of elements in a list. You can specify the start and
stop indices, and Python returns a new list containing the specified elements.
Syntax: list_name[start:stop:step]
Modifying List
Lists are mutable, meaning you can change their content after creation. You can add,
remove, or change elements in a list.
Changing an element
fruits[1] = "blueberry"
print(fruits) Output: ['apple', 'blueberry', 'cherry']
Adding an element
fruits.append("mango")
print(fruits) Output: ['apple', 'blueberry', 'cherry’,
'mango']
Removing an element
fruits.remove("cherry")
print(fruits) Output: ['apple', 'blueberry', 'mango']
List Methods
Python provides several built-in methods to modify and operate on lists. Eg:
List Comprehensions
List comprehensions provide a concise way to create lists. They consist of brackets
containing an expression followed by a for clause, and optionally if clauses.
Syntax:
new_list = [expression for item in iterable if condition]
Using for
loop for fruit in
fruits:
print(fruit)
Chapter - 17
Tuple in Python
• What is Tuple
• Create Tuples
• Access Tuples: Indexing & Slicing
• Tuple Operations
• Tuple Iteration
• Tuple Methods
• Tuple Functions
• Unpack Tuples
• Modify Tuple
Tuple in Python
A tuple is a collection of items in Python that is ordered, unchangeable (immutable)
and allow duplicate values.
Tuples are used to store multiple items in a single variable.
Note: Ordered – Tuple items have a defined order, but that order will not change.
Example:
fruits = ("apple", "orange", "cherry", "apple")
print(fruits)
Output: ('apple', 'orange', 'cherry', 'apple')
4. Single-Item Tuple
tuplesingle = ("only",)
You can access elements in a tuple by referring to their index. Python uses zero-based
indexing, meaning the first element has an index of 0.
Syntax: tuple_name[index]
Example:
fruits = ("apple", "orange", "cherry", "apple", "mango")
Tuple Slicing
Slicing allows you to access a range of elements in a tuple. You can specify the start and
stop indices, and Python returns a new tuple containing the specified elements.
Syntax: tuple_name[start:stop:step]
Tuple Operations
1. Concatenation
You can join two or more tuples using the + operator.
tuple1 = (1, 2, 3)
tuple2 = (4, 5)
combined = tuple1 + tuple2
print(combined) Output: (1, 2, 3, 4, 5)
2. Repetition
You can repeat a tuple multiple times using the *
operator.
tuple3 = ("hello",) * 3
print(tuple3) Output: ('hello', 'hello', 'hello’)
Using for
loop for fruit in
fruits:
print(fruit)
i = 0
while i < len(fruits):
print(fruits[i])
index += 1
Tuple Methods
Python provides two built-in methods to use on tuples.
count
colors = ("red", "green", "blue",
"green") print(colors.count("green"))
Output:
2
index
colors = ("red", "green", "blue",
"green") print(colors.index("blue"))
Output: 2
Tuple Functions
Python provides several built-in functions to use on tuples.
print(len(numbers)) Output: 4
sorted_num = sorted(numbers)
print(sorted_num) Output:
[1,2,3,4]
print(sum(numbers 1
)) Output: 0
print(min(numbers 1
)) Output:
print(max(numbers 4
)) Output:
a = "Madhav"
b = 21
c = "Engineer"
pack_tuple = a,b,c Packing values into a tuple
print(pack_tuple)
Once a tuple is created, you cannot modify its elements. This means you cannot add,
remove, or change items.
Creating a tuple
numbers = (1, 2, 3)
Chapter - 18
Set in Python
• What is a Set
• Create Sets
• Set Operations
• Set Methods
• Set Iteration
• Set Comprehensions
Set in Python
A set is a collection of unique items in Python. Sets do not allow duplicate items and do
not maintain any particular order so it can’t be indexed.
Characteristics of Sets:
Unordered: Elements have no defined order. You cannot access elements by index.
Unique Elements: No duplicates allowed. Each element must be distinct.
Mutable: You can add or remove elements after creation.
Immutable Elements: individual elements inside a set cannot be modified/replaced
Example:
vowels = {'a', 'e', 'i', 'o', 'u'}
Set Operations
1. Adding Elements : Use the add() method to add a single element to a set.
fruits = {'apple', 'banana'}
fruits.add('cherry')
print(fruits) Output: {'apple', 'banana', 'cherry’}
Using remove()
fruits.remove('banana')
print(fruits) Output: {'apple', 'cherry'}
Using discard()
fruits.discard('oran No error even ifi no
ge') 'orange' is t
in the set
print(fruits) {'apple', 'cherry’}
Output:
Set Methods
1. Union: Combines elements from two sets, removing duplicates.
set_a = {1, 2, 3}
set_b = {3, 4, 5}
union_set = set_a.union(set_b)
print(union_set) Output: {1, 2, 3,
4, 5}
3. Difference: Elements present in the first set but not in the second.
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5}
difference_set =
set_a.difference(set_b)
print(difference_set) Output: {1,
2}
set_a = {1, 2, 3}
set_b = {3, 4, 5}
sym_diff_set =
set_a.symmetric_difference(set_b)
print(sym_diff_set) Output: {1, 2, 4,
5}
Using while loop - first convert set to a list then use while loop
because sets do not support indexing.
Syntax:
new_set = {expression for item in iterable if condition}
Example:
squares = {x**2 for x in range(1,
6)} print(squares) Output: {1, 4,
9, 16, 25}
Chapter - 19
Dictionary in Python
• What is a Dictionary
• Create Dictionary
• Access Dictionary Values
• Dictionary Methods
• Dictionary – Add, Modify & Remove Items
• Dictionary Iteration
• Nested Dictionary
• Dictionary Comprehensions
Dictionary in Python
A dictionary is a data structure in Python that stores data in key-value pairs. Dictionary
items (key – value pair) are ordered, changeable, and do not allow duplicates.
Key: Must be unique and immutable (strings, numbers, or tuples).
Value: Can be any data type and does not need to be unique.
Syntax
my_dict =
{"key1": "value1", "key2": "value2", "key3": "value3",
…}
Exampl
e:
student = {
1: "Class-X",
"name": "Madhav",
"age": 20
}
Dictionary Methods
Python provides several built-in methods to use on dictionary.
Examples
print(student.keys()) All keys
print(student.values() All values
)
print(student.items()) All key-value
pairs
print(student.get("name")) Safie way to access a value
Dictionary Iterations
A dictionary can be iterated using for loop. We can loop through dictionaries by keys,
values, or both.
Dictionary Comprehension
A dictionary comprehension allows you to create dictionaries in a concise way.
Syntax:
new_dict =
{key_expression: value_expression for item in iterable if
condition}
Chapter - 20
OOPs in Python
• What is OOPs
• Why OOP is required
• Class and Object
• Attributes and Methods
• init Method (Constructor)
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
OOPs in Python
Two ways of programming in Python:
1) Procedural Programming,
2) OOPs
Why OOPs?
• Models Real-World Problems:
Mimics real-world entities for easier understanding.
• Code Reusability:
Encourages reusable, modular, and organized code.
• Easier Maintenance:
OOP organizes code into small, manageable parts (classes and objects). Changes
in one part don’t impact others, making it easier to maintain.
• Encapsulation:
Encapsulation protects data integrity and privacy by bundling data and methods
within objects.
• Flexibility & Scalability:
OOP makes it easier to add new features without affecting existing code.
def student_details(self):
super().student_details()
print(f"Stream: {self.stream}")
Example
class GraduateStudent(Student):
def student_details(self): Same method as in
parent class
print(f"{self.name} is a graduate student from final
year.")
Polymorphism in action
student1 = Student("Madhav", 10, 98)
grad_student = GraduateStudent("Sudevi", 12, 99, "flCM")
student1.student_details()
Output: adhav is in 10 grade with 98%
P y thon No te s by Ris habh Mish
ra
grad_student.student_details()
Output: Sudevi is a graduate student firom fiinal year.
Chapter - 21
Modules in Python
A module is a single Python file (.py) containing Python code. It can include functions,
classes, and variables that you can reuse in other programs.
# Create a module:
• Save the following as mymodule.py
def say_hello(name):
return print(f"Hello, {name}!")
# Structure Example:
my_package/
init .py
math_utils.py
string_utils.py
Libraries in Python
A library is a collection of modules and packages that provide pre-written functionality for
your program. Libraries are typically larger and more feature-rich than packages or
modules.
pip stands for "Pip Installs Packages". It is the package manager for Python that allows
you to install, update, and manage Python libraries (packages) from the Python Package
Index (PyPI).
Think of pip as an app store for Python libraries. You use it to search, install, and manage
Python tools, just like downloading apps on your phone.
Scientific computing
Data SciPy and technical install numpy
Analytics computing.
Statistical modeling and pip install scipy
Statsmodels testing.
Parallel computing for pip install
Dask large datasets.
statsmodels pip
install dask
Gradient boosting
XGBoost for structured data. pip install xgboost
Chapter - 22
Open a File
To perform any operation (read/write) on a file, you first need to open the file using
Python’s open() function.
File Modes:
• 'r': Read (default mode). Opens the file for reading.
• 'w': Write. Opens the file for writing (if file doesn’t exist, it creates one).
• 'a': Append. Opens the file for appending (if file doesn’t exist, it creates one).
• 'rb'/'wb': Read/Write in binary mode.
Once a file is open, you can read from it using the following methods:
• read(): Reads the entire content of the file.
• readline(): Reads one line from the file at a time.
• readlines(): Reads all lines into a list.
Write to a File
# Close a file:
file.closv()
Close a File
Instead of manually opening and closing a file, you can use the with statement, which
automatically handles closing the file when the block of code is done.