Python Notes by Risabh Mishra
Python Notes by Risabh Mishra
Source: www.youtube.com/@RishabhMishraOfficial
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.
P y t h o n N o t e s b y R i s h a b h M i s h ra
Popular programming languages
As per statista survey, Python is the most popular programming language.
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.
P y t h o n N o t e s b y R i s h a b h M i s h ra
Ques2: Write a program to print numbers from 1 to 10
In above examples we can see that Python is simple in writing & reading the code.
P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial
Chapter - 02
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
P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial
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
P y t h o n N o t e s b y R i s h a b h M i s h ra
Comments: Comments are used to annotate codes, and they are not
interpreted by Python. It starts with the hash character #
Comments are used as notes or short descriptions along with the code to increase
its readability.
P y t h o n N o t e s b y R i s h a b h M i s h ra
Python Code Execution Steps
1. Lexical Analysis: The interpreter breaks down the code into smaller parts
called tokens, identifying words, numbers, symbols, and punctuation.
2. Syntax Parsing: It checks the structure of the code to ensure it follows the
rules of Python syntax. If there are any errors, like missing parentheses or
incorrect indentation, it stops and shows a SyntaxError.
3. Bytecode Generation: Once the code is validated, the interpreter translates
it into a simpler set of instructions called bytecode. This bytecode is easier
for the computer to understand and execute.
4. Execution by PVM: The Python Virtual Machine (PVM) takes the bytecode
and runs it step by step. It follows the instructions and performs calculations,
assigns values to variables, and executes functions.
5. Error Handling and Output: If there are any errors during execution, like
trying to divide by zero or accessing a variable that doesn't exist, the
interpreter raises an exception. If the code runs without errors, it displays
any output, such as printed messages or returned values, to the user.
Python Syntax
The syntax of the Python programming language, is the set of rules that defines
how a Python program will be written and interpreted (by both the runtime system
& by human readers).
my_name = "Madhav"
my_name = Madhav
# Use quotes "" for strings in Python
P y t h o n N o t e s b y R i s h a b h M i s h ra
Interpreter vs Compiler
Interpreter Compiler
An interpreter translates and A compiler translates the entire code
executes a source code line by line into machine code before the
as the code runs. program runs.
P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial
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.
PythonLevel = "Beginner" # pascal case
pythonLevel = "Beginner" # camel case
pythonlevel = "Beginner" # flat case
python_level = "Beginner" # Snake case
P y t h o n N o t e s b y R i s h a b h M i s h ra
x = 10
print(x+1) # add number to a variable
a, b, c = 1, 2, 3
print(a, b, c) # assign multiple variables
_my_name = "Madhav"
for = 26
# ‘for’ is a reserved word in Python
P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial
Chapter - 05
P y t h o n N o t e s b y R i s h a b h M i s h ra
Python Tutorial Playlist: Click Here
https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9
P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial
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()
P y t h o n N o t e s b y R i s h a b h M i s h ra
# Converting Float to Integer:
float_num = 108.56
int_num = int(float_num)
print(int_num) # Output: 108
print(type(int_num)) # Output: <class 'int'>
Types of Typecasting
There are two types of type casting in python:
• Implicit type casting
• Explicit type casting
P y t h o n N o t e s b y R i s h a b h M i s h ra
int_num = int(str_num)
print(int_num) # Output: 26
print(type(int_num)) # Output: <class 'int’>
P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial
Chapter - 07
P y t h o n N o t e s b y R i s h a b h M i s h ra
# Since input() returns a string, we need to convert it to an integer
num1 = int(num1)
num2 = int(num2)
# Calculating the sum and display the result
P y t h o n N o t e s b y R i s h a b h M i s h ra
Python Tutorial Playlist: Click Here
https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial
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
7. Membership Operators
P y t h o n N o t e s b y R i s h a b h M i s h ra
Operators Cheat Sheet
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.
P y t h o n N o t e s b y R i s h a b h M i s h ra
Precedence of Arithmetic Operators in Python:
P – Parentheses
E – Exponentiation
M – Multiplication
D – Division
A – Addition
S – Subtraction
3. Assignment Operators
Assignment operators are used to assign values to variables.
P y t h o n N o t e s b y R i s h a b h M i s h ra
4. Logical Operators
Logical operators are used to combine conditional statements.
6. Bitwise Operators
Bitwise operators perform operations on binary numbers.
P y t h o n N o t e s b y R i s h a b h M i s h ra
Bitwise Operators Example:
# Compare each bit in these numbers. Eg:1
P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial
Chapter - 09
P y t h o n N o t e s b y R i s h a b h M i s h ra
1. 'if' Conditional Statement
The if statement is used to test a condition and execute a block of code only if
the condition is true.
Syntax:
if condition:
# Code to execute if the condition is true
Example:
age = 26
if age > 19:
print("You are an adult")
P y t h o n N o t e s b y R i s h a b h M i s h ra
2. 'if-else' Conditional Statement
The if-else statement provides an alternative block of code to execute if the
condition is false.
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.")
P y t h o n N o t e s b y R i s h a b h M i s h ra
3. 'if-elif-else' Conditional Statement
The if-elif-else statement allows to check multiple conditions and execute
different blocks of code based on which condition is true.
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")
P y t h o n N o t e s b y R i s h a b h M i s h ra
Syntax:
if condition1:
# Code block for condition1 being True
if condition2:
# Code block for condition2 being True
else:
# Code block for condition2 being False
else:
# Code block for condition1 being False
... ..
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 if 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 t h o n N o t e s b y R i s h a b h M i s h 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 = None
if value:
print("Value is True")
else:
print("Value is False")
P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial
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 :)
P y t h o n N o t e s b y R i s h a b h M i s h ra
Syntax:
# return result is optional, Use if you want the function to give back a value
P y t h o n N o t e s b y R i s h a b h M i s h ra
Function with Parameters
Example:2
# Output: 8
P y t h o n N o t e s b y R i s h a b h M i s h ra
# function to convert Celsius to Fahrenheit
def celsius_to_fahrenheit(celsius):
fahrenheit = (celsius * 9/5) + 32
return Fahrenheit
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.
P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial
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.
P y t h o n N o t e s b y R i s h a b h M i s h ra
Required Arguments (same as above)
Required arguments are the arguments passed to a function in correct positional order. 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
P y t h o n N o t e s b y R i s h a b h M i s h ra
result = divide(10, 20) # positional arguments
print(result) # Output: 0.5
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(*names):
for name in names:
print(f"Hello, {name}!")
greetings("Madhav", "Rishabh", "Visakha")
# Output:
Hello, Madhav!
Hello, Rishabh!
Hello, Visakha!
P y t h o n N o t e s b y R i s h a b h M i s h ra
Example 1:
def print_details(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
# Output:
name: Madhav
age: 26
city: Delhi
Example 2:
def shopping_cart(**products):
total = 0
print("Items Purchased:")
for item, price in products.items():
print(f"{item}: ₹{price}")
total += price
print(f"Total: ₹{total}")
# Output:
Items Purchased:
apple: ₹15
orange: ₹12
mango: ₹10
Total: ₹37
P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial
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:
P y t h o n N o t e s b y R i s h a b h M i s h ra
Formatted String - % Operator
Old-style formatting (% operator)
This approach uses the % operator and is similar to string formatting in languages like C.
Example:
name = "Madhav"
age = 16
print("My name is %s and I’m %d." % (name, age))
# %s, %d are placeholders for strings and integers
Example:
name = "Madhav"
age = 16
print("My name is {} and I’m {}.".format(name, age))
# You can also reference the variables by index or keyword:
print("My name is {0} and I’m {1}.".format(name, age))
print("My name is {name} and I’m {age}.".format(name="Madhav",
age=28))
P y t h o n N o t e s b y R i s h a b h M i s h ra
Formatted String – F-strings
F-strings (formatted string literals)
In Python 3.6, F-strings are the most concise and efficient way to format strings. You
prefix the string with an f or F, and variables or expressions are embedded directly within
curly braces {}.
Example:
name = "Madhav"
age = 16
print(f"My name is {name} and I’m {age}.")
# You can also perform 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:
P y t h o n N o t e s b y R i s h a b h M i s h ra
String Operators
P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial
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"
P y t h o n N o t e s b y R i s h a b h M i s h ra
String Indexing – Positive & Negative Index
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'
P y t h o n N o t e s b y R i s h a b h M i s h ra
String Slicing - Examples
Example:
name = "MADHAV"
String Methods
P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial
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 from 0 to 3
count = 0
while count < 4: # Condition
print(count)
count += 1
# Output: 0 1 2 3
P y t h o n N o t e s b y R i s h a b h M i s h ra
While Loop Example
else Statement: An else clause can be added to loops. It executes after the loop
finishes normally (i.e., not terminated by break). Example:
count = 3
while count > 0: # Condition
print("Countdown:", count)
count -= 1
else:
print("Liftoff!") # Run after while loop ends
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
language = 'Python’
for x in language:
print(x) # Output: P y t h o n
P y t h o n N o t e s b y R i s h a b h M i s h ra
range() Function Example
Example1: Basic usage with One Argument - Stop
for i in range(5):
print(i)
# Output: 0 1 2 3 4
Example2: Basic usage with Start, Stop and Step
for i in range(1, 10, 2):
print(i)
# Output: 1 3 5 7 9
Example:
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.
P y t h o n N o t e s b y R i s h a b h M i s h ra
Loop Control Statements
Loop control statements allow you to alter the normal flow of a loop.
Python supports 3 clauses within loops:
• pass statement
• break Statement
• continue Statement
Example:
for i in range(5):
# code to be updated
pass
Above example, the loop executes without error using pass statement
Example:
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
P y t h o n N o t e s b y R i s h a b h M i s h ra
Loop Control - continue Statement
continue Statement: The continue statement skips the current iteration and moves
to the next one.
Example:
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 t h o n N o t e s b y R i s h a b h M i s h ra
Validate User Input
# validate user input: controlled infinite while loop using
break statement
while True:
user_input = input("Enter 'exit' to STOP: ")
if user_input == 'exit':
print("congarts! You guessed it right!")
break
print("sorry, you entered: ", user_input)
P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial
Chapter - 15
Syntax:
Outer_loop:
inner_loop:
# Code block to execute - inner loop
# Code block to execute - outer loop
P y t h o n N o t e s b y R i s h a b h M i s h ra
Nested Loop Example
Example: Print numbers from 1 to 3, for 3 times using for-for
nested loop
i = 1
while i < 4: # Outer while loop (runs 3 times)
for j in range(1, 4):
print(j)
print()
i += 1
P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial
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']
P y t h o n N o t e s b y R i s h a b h M i s h ra
Accessing List Elements - Indexing
You can access elements in a list by referring to their index. Python uses zero-based
indexing, meaning the first element has an index of 0.
Syntax: list_name[index]
Example:
fruits = ["apple", "orange", "cherry", "apple", "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]
P y t h o n N o t e s b y R i s h a b h M i s h ra
# Reverse list
print(numbers[::-1]) # Output: [60,50,40,30,20,10]
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:
P y t h o n N o t e s b y R i s h a b h M i s h ra
Join Lists
There are several ways to join, or concatenate, two or more lists in Python.
list1 = [1, 2]
list2 = ["a", "b"]
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]
P y t h o n N o t e s b y R i s h a b h M i s h ra
List Comprehensions - Flatten a List
P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial
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')
1. Using Parentheses ()
colors = ("red", "green", "blue")
numbers = (1, 2, 3, 4, 5)
mixed = (1, "hello", 3.14, True)
nested = (1, [2, 3], (4, 5, 6))
P y t h o n N o t e s b y R i s h a b h M i s h ra
2. Without Parentheses (Comma-Separated)
also_numbers = 1, 2, 3, 4, 5
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]
P y t h o n N o t e s b y R i s h a b h M i s h ra
Example:
numbers = (10, 20, 30, 40, 50, 60)
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’)
P y t h o n N o t e s b y R i s h a b h M i s h ra
Iterating Over Tuple
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.
P y t h o n N o t e s b y R i s h a b h M i s h ra
numbers = (2, 3, 1, 4)
print(len(numbers)) # Output: 4
sorted_num = sorted(numbers)
print(sorted_num) # Output: [1,2,3,4]
print(sum(numbers)) # Output: 10
print(min(numbers)) # Output: 1
print(max(numbers)) # Output: 4
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)
P y t h o n N o t e s b y R i s h a b h M i s h ra
Modifying Tuple
But there is a trick. You can convert the tuple into a list, change the list, and convert the
list back into a tuple.
P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial
Assignment - 03
Sol 1:
# User input
year = int(input("Enter a year (e.g. 2024): "))
# Check if the year is a leap year
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
P y t h o n N o t e s b y R i s h a b h M i s h ra
Q2: Login Authentication
Login Authentication using conditional statement. Assume you have a predefined
username and password.
Write a program that prompts the user to enter a username and password and
checks whether they match. Provide appropriate messages for the following
cases:
• Both username and password are correct.
• Username is correct but password is incorrect.
• Username is incorrect.
Sol 2:
# Predefined username and password
predefined_username = "madhav"
predefined_password = "pass101"
# Prompt the user for username and password
input_username = input("Enter username: ")
input_password = input("Enter password: ")
# Check the username and password
if input_username == predefined_username:
if input_password == predefined_password:
print("Welcome! Login was successful.")
else:
print("Login failed: Incorrect password.")
else:
print("Login failed: Incorrect username.")
P y t h o n N o t e s b y R i s h a b h M i s h ra
Q3: Admission Eligibility
A university has the following eligibility criteria for admission:
• Marks in Mathematics >= 65
• Marks in Physics >= 55
• Marks in Chemistry >= 50
• Total marks in all three subjects >= 180 OR Total marks in Mathematics and
Physics >= 140
Write a program that takes marks in three subjects as input and prints whether the
student is eligible for admission.
Sol 3:
# Input marks from the user
print("Enter below PCM marks out of 100")
physics_marks = int(input("Physics: "))
chemistry_marks = int(input("Chemistry: "))
math_marks = int(input("Maths: "))
# Check the eligibility criteria
if (math_marks >= 65 and
physics_marks >= 55 and
chemistry_marks >= 50 and
(math_marks + physics_marks + chemistry_marks) >= 180) or
\
(math_marks + physics_marks) >= 140:
print("Eligible for admission!")
else:
print("Not eligible for admission")
P y t h o n N o t e s b y R i s h a b h M i s h ra
Python Tutorial Playlist: Click Here
https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9