0% found this document useful (0 votes)
4 views

Python (Preview Only)

This document expresses gratitude to contributors of a Python learning book, emphasizing the importance of community support and the aim to make Python accessible for beginners. It outlines the book's structure, including chapters on variables, input handling, and various programming concepts, with a focus on practical examples and clarity. The preface highlights the goal of simplifying Python learning and fostering a deeper understanding of coding principles.

Uploaded by

ssgaca12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python (Preview Only)

This document expresses gratitude to contributors of a Python learning book, emphasizing the importance of community support and the aim to make Python accessible for beginners. It outlines the book's structure, including chapters on variables, input handling, and various programming concepts, with a focus on practical examples and clarity. The preface highlights the goal of simplifying Python learning and fostering a deeper understanding of coding principles.

Uploaded by

ssgaca12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 105

‭Acknowledgement‬

I‭ would like to express my deepest gratitude to all those who have‬


‭contributed to the creation of this Book.‬

‭ irst and foremost, I extend my sincere thanks to the readers for their‬
F
‭interest in learning Python and for choosing this Book as a resource. Your‬
‭enthusiasm for coding is what drives the continued effort to create‬
‭meaningful educational content.‬

‭ special acknowledgment goes to my mentors, peers, and the‬


A
‭programming community for their invaluable support and inspiration. Their‬
‭guidance and feedback have been instrumental in shaping my journey as a‬
‭programmer and in the development of this Book.‬

I‭ also owe a debt of gratitude to the countless developers and educators‬


‭whose work has paved the way for accessible programming knowledge.‬
‭Their contributions to the field have made it possible for resources like this‬
‭to exist.‬

‭ astly, I dedicate this Book to all aspiring programmers who, like me, share‬
L
‭a passion for coding. May this book serve as a stepping stone in your‬
‭journey to mastering Python and unlocking new possibilities in the world of‬
‭technology.‬

‭With gratitude,‬

‭ alam‬
S
‭2nd Year Python Programmer‬
‭Contents‬
‭Table of Contents‬

‭ l. No.
S Chapter‬ ‭Page No.‬
‭--------------------------------------------------------------------------------------------------‬
‭1‬ ‭VARIABLES 4 - 12‬

‭2‬ ‭TAKING INPUTS‬ ‭13 - 20‬

‭3‬ ‭IF ELSE/ELIF‬ ‭21 - 32‬

‭4‬ ‭LOOPS‬ ‭33 - 66‬

‭5‬ ‭LISTS‬ ‭67 - 116‬

‭6‬ ‭FUNCTIONS 117 - 192‬

‭7‬ ‭FILE HANDLING 193 - 246‬

‭8‬ ‭BASICS OF OOP 247 - 263‬


‭Preface‬
‭ elcome to this journey into the world of Python—a language that‬
W
‭powers everything from simple scripts to complex AI systems. This‬
‭book was crafted with one goal in mind: to make Python effortless and‬
‭enjoyable to learn, whether you're a complete beginner or someone‬
‭looking to sharpen your skills.‬

I‭n a world flooded with tutorials that confuse more than they clarify, I‬
‭wanted to create something different—a course that speaks your‬
‭language, cuts through the noise, and builds your confidence line by‬
‭line. You won’t just memorize syntax here—you’ll understand how‬
‭things work under the hood and why they matter.‬

‭ e start from zero—no prior coding knowledge needed—and go all‬


W
‭the way to mastering core concepts like functions, loops,‬
‭object-oriented programming, file handling, and beyond. I’ve broken‬
‭everything down into bite-sized explanations with real-world examples‬
‭that stick.‬

‭ ython is more than code—it's a tool for thinking clearly. And my‬
P
‭mission is to help you unlock that clarity with simplicity, logic, and a‬
‭touch of creativity.‬

‭ o take a deep breath, stay curious, and let’s write your first line of‬
S
‭code together.‬

‭Let’s begin.‬
‭Chapter 1: Variables‬
‭Definition:‬
‭ variable in Python is a name that refers to a value stored in memory.‬
A
‭It acts as a container to hold data that can be used and modified‬
‭during program execution.‬

‭Example (Declaring a Variable):‬


‭ Declaring variables in Python‬
#
‭name = "Alice" # String variable‬
‭age = 25 # Integer variable‬
‭height = 5.7 # Float variable‬
‭is_student = True # Boolean variable‬

‭Rules for Naming Variables:‬


‭●‬ V
‭ ariable names can only contain letters (A–Z, a–z), digits (0–9),‬
_‭.‬‬
‭and underscores‬‭

‭●‬ A
‭ variable name must start with a letter or an underscore,‬‭not‬‭a‬
‭number.‬

‭●‬ V ‭ ariable names are‬‭case-sensitive‬‭(‬‭


name‬‭and‬‭Name‬‭are‬
‭different).‬
‭●‬ ‭Reserved words (like‬‭ if‬ else‬
‭,‬‭ while‬
‭,‬‭ class‬
‭,‬‭ ‭, etc.) cannot be‬
‭used as variable names.‬
‭●‬ ‭Choose meaningful names to make your code readable.‬

‭Examples of valid variable names‬


‭student_name = "John"‬
‭_age = 18‬
‭marks2025 = 90‬
‭Examples of invalid variable names:‬
‭ name = "John" # Cannot start with a number‬
2
‭student-name = "John" # Cannot use hyphens‬
‭class = "Python" # 'class' is a reserved word‬

‭Types of Variables (Basic):‬


‭String (‬‭
str‬‭)‬‭: Text enclosed in quotes.‬
‭name = "Alice"‬

‭●‬ ‭Integer (‬‭ int‬‭)‬‭: Whole numbers without decimals.‬


‭age = 25‬
‭●‬ ‭Float (‬‭ float‬ ‭)‬‭: Numbers with decimal points.‬
‭height = 5.7‬
‭●‬ ‭Boolean (‬‭ bool‬ True‬‭or‬‭
‭)‬‭: Represents‬‭ False‬
‭.‬
‭is_student = True‬

print()‬‭Function‬
‭The‬‭

print()‬‭function is used to output data to the screen.‬


‭The‬‭
‭Example:‬

‭print("Hello, World!")‬
‭Output:‬
‭Hello, World!‬
‭Programs:‬
‭ .‬‭Declare a variable to store your name and print‬‭it.‬
1
‭name = "Alice"‬
‭print(name)‬
‭Output:‬
‭Alice‬

age‬‭and‬‭
‭2.‬‭Declare two variables,‬‭ height‬
‭, and print them‬
‭together.‬

‭ ge = 25‬
a
‭height = 5.6‬
‭print(age, height)‬

‭Output:‬
‭25 5.6‬

is_student‬‭and print it.‬


‭3.‬‭Declare a boolean variable‬‭

i‭s_student = True‬
‭print(is_student)‬
‭Output:‬
‭True‬

#‭.‬‬
‭4.‬‭Print "Python", "is", "awesome" separated by‬‭
‭print("Python", "is", "awesome", sep="#")‬
‭Output:‬
‭Python#is#awesome‬

Hello‬‭and‬‭
‭5.‬‭Print two statements‬‭ World‬‭on the same line.‬

‭ rint("Hello", end=" ")‬


p
‭print("World")‬
‭Output:‬
‭Hello World‬

‭6.‬‭Print following using a single print statement:‬


‭Good Morning‬
‭print("Good\nMorning")‬

‭Output:‬
‭ ood‬
G
‭Morning‬

‭7.‬‭Declare variables for‬‭city = "Paris"‬‭and‬‭


country =‬
"France"‬
‭ City: Paris, Country: France‬
‭, then print:‬‭ ‭.‬

‭ ity = "Paris"‬
c
‭country = "France"‬
‭print("City:", city, ", Country:", country)‬
‭Output:‬
‭City: Paris , Country: France‬

‭8.‬‭Question:‬
‭Print the following using a newline (‬‭
\n‬‭) between‬‭words:‬
‭Welcome‬
‭to‬
‭Python‬
‭Answer:‬
‭print("Welcome\to\nPython")‬

‭Output:‬
‭ elcome‬
W
‭to‬
‭Python‬

‭9.‬ ‭Print the following using tab spaces (‬‭


\t‬‭) between‬‭words:‬

‭ ame Age Country‬


N
‭Answer:‬
‭print("Name\tAge\tCountry")‬‭Output:‬
‭Name Age Country‬

‭10.‬‭Question:‬
a‬‭and‬‭
‭ wap the values of two variables‬‭
S b‬‭without‬‭using a third‬
‭variable, and print the result.‬
‭Answer:‬
‭ = 5‬
a
‭b = 10‬
‭a, b = b, a # Swapping the values‬
‭print("a:", a)‬
‭print("b:", b)‬
‭Output:‬
‭a: 10‬
‭b: 5‬

‭11.‬‭Question:‬
‭ eclare three variables and perform multiple assignment (all at once)‬
D
‭to store values in them. Print their values.‬
‭Answer:‬
‭ , y, z = 3, 6, 9‬
x
‭print("x:", x)‬
‭print("y:", y)‬
‭print("z:", z)‬

‭Output:‬
‭ : 3‬
x
‭y: 6‬
‭z: 9‬

‭12.‬‭Question:‬
‭ reate a program where two variables‬‭
C x = 100‬‭and‬‭
y = 50‬‭are‬
‭added and printed together as the result.‬
‭Answer:‬
‭ = 100‬
x
‭y = 50‬
‭sum_result = x + y‬
‭print("Sum:", sum_result)‬
‭Output:‬
‭Sum: 150‬

‭13.‬‭Question:‬
‭ reate a program where two strings are concatenated, and the result‬
C
‭is printed.‬
‭Answer:‬
‭ tr1 = "Hello"‬
s
‭str2 = "World"‬
‭result = str1 + " " + str2 # Concatenating strings‬
‭print(result)‬

‭Output:‬
‭Hello World‬

‭14.‬‭Question:‬
input()‬‭function to accept a user’s name‬‭and print it with a‬
‭ se the‬‭
U
‭message.‬
‭Answer:‬
‭ ame = input("Enter your name: ")‬
n
‭print("Hello, " + name + "!")‬
‭Output:‬
‭Enter your name: Alice‬
‭Hello, Alice!‬
‭15.‬‭Question:‬
‭ reate a program that calculates the area of a rectangle with length‬
C
‭10 and width 5. Print the area.‬
‭Answer:‬
l‭ength = 10‬
‭width = 5‬
‭area = length * width‬
‭print("Area of the rectangle:", area)‬

‭Output:‬
‭Area of the rectangle: 50‬

‭16.‬‭Question:‬
‭ erform an arithmetic operation (multiplication) between an integer‬
P
‭and a float, and print the result.‬
‭Answer:‬
i‭nteger = 7‬
‭floating_point = 2.5‬
‭result = integer * floating_point‬
‭print("Result of multiplication:", result)‬

‭Output:‬
‭Result of multiplication: 17.5‬
‭Chapter 2: Taking Inputs‬
input()‬‭Function‬
‭1.The‬‭
‭Definition:‬

‭ he‬‭
T input()‬‭function allows the user to enter data,‬‭which is always‬
‭returned as a‬‭string‬‭.‬
‭Example:‬
‭ Taking input from the user‬
#
‭name = input("Enter your name: ")‬

‭ Displaying the input‬


#
‭print(name)‬

‭Output:‬
‭ nter your name: Alice‬
E
‭Alice‬

‭Usage:‬

input()‬
‭●‬ ‭To‬‭accept user input‬‭, you use‬‭ ‭.‬

‭●‬ T
‭ he function always returns the input as a‬‭string‬‭,‬‭even if the‬
‭user types in numbers. You can convert it to other data types if‬
int‬‭or‬‭
‭needed (like‬‭ float‬
‭).‬

‭2. String (‬‭


str‬
‭)‬
‭●‬ ‭Example‬‭: Taking a string input and printing it.‬

‭ Taking string input from the user‬


#
‭name = input("Enter your name: ")‬

‭ Printing the user input‬


#
‭print( name)‬

‭Alice‬

‭3. Integer (‬‭


int‬
‭)‬

‭●‬ ‭Example‬‭: Taking an integer input and printing it.‬

‭ Taking integer input from the user‬


#
‭age = int(input("Enter your age: "))‬

‭ Printing the user input‬


#
‭print("Your age is:", age)‬

‭Output:‬
‭ nter your age: 25‬
E
‭Your age is: 25‬

‭4. Float (‬‭


float‬
‭)‬

‭●‬ ‭Example‬‭: Taking a float input and printing it.‬

‭ Taking float input from the user‬


#
‭height = float(input("Enter your height: "))‬
‭ Printing the user input‬
#
‭print("Your height is:", height)‬

‭Output:‬
‭ nter your height: 5.8‬
E
‭Your height is: 5.8‬

‭5. Boolean (‬‭


bool‬
‭)‬

‭●‬ ‭Example‬‭: Taking a boolean input and printing it.‬

input()‬‭always returns a string, we need to‬‭explicitly convert it‬


‭ ince‬‭
S
‭to a boolean.‬
‭ Taking boolean input from the user‬
#
‭is_adult = input("Are you an adult? (True/False): ")‬

‭ Converting the input to boolean‬


#
‭is_adult = is_adult.lower() == 'true'‬

‭ Printing the user input‬


#
‭print("Adult status:", is_adult)‬

‭Output:‬
‭ re you an adult? (True/False): True‬
A
‭Adult status: True‬

‭Summary:‬
‭1.‬‭String (‬‭
str‬ input()‬‭takes the input as a string.‬
‭)‬‭:‬‭

‭2.‬‭Integer (‬‭
int‬ int()‬
‭)‬‭: Convert the input to an integer using‬‭ ‭.‬

‭3.‬‭Float (‬‭
float‬ float()‬
‭)‬‭: Convert the input to a float using‬‭ ‭.‬

‭4.‬‭Boolean (‬‭
bool‬‭)‬‭: Convert the input to boolean by checking if it‬
"true"‬
‭equals‬‭ ‭.‬

‭TYPE CONVERSIONS‬

‭1. String to Integer‬


‭ um_str = "100"‬
n
‭num_int = int(num_str)‬
‭print(num_int)‬
‭Output:‬
‭100‬

‭2. Integer to Float‬


‭ um_int = 7‬
n
‭num_float = float(num_int)‬

‭print(num_float)‬

‭Output:‬
‭7.0‬

‭3. Float to Integer‬


‭ um_float = 8.9‬
n
‭num_int = int(num_float)‬

‭ rint(num_int)‬
p
‭Output:‬
‭8‬
‭4. Boolean to Integer‬
f‭lag = True‬
‭num = int(flag)‬

‭print(num)‬

‭Output:‬
‭1‬

‭5. Integer to String‬


‭ um = 25‬
n
‭text = str(num)‬

‭print(text)‬

‭Output:‬
‭25‬

‭1. Taking Multiple Inputs in a Single Line‬


‭ Taking multiple inputs from the user‬
#
‭a, b = input("Enter two numbers: ").split()‬

‭ rint(a)‬
p
‭print(b)‬
‭Example Input:‬
‭Enter two numbers: 10 20‬

‭Output:‬
‭ 0‬
1
‭20‬

‭2. Taking Multiple Inputs and Converting to Integer‬


‭ Taking multiple integer inputs‬
#
‭a, b = map(int, input("Enter two integers: ").split())‬

‭ rint(a)‬
p
‭print(b)‬

‭Example Input:‬
‭Enter two integers: 5 15‬
‭Output:‬
‭5‬
‭15‬

‭Key Points:‬

‭●‬ ‭
input().split()‬‭separates the inputs by spaces.‬

‭●‬ m
‭ap(type, input().split())‬‭applies type conversion‬‭(like‬
int‬
‭ float‬
‭,‬‭ ‭) to all inputs.‬
‭PROGRAMS‬
‭1.Q. Take a string input from the user and print it.‬
‭ ame = input("Enter your name: ")‬
n
‭print(name)‬

‭2.‬‭Q. Take an integer input from the user and print‬‭it.‬


‭ ge = int(input("Enter your age: "))‬
a
‭print(age)‬

‭3.Q. Take a float input from the user and print it.‬
‭ eight = float(input("Enter your height: "))‬
h
‭print(height)‬

‭ .‬‭Q. Take a boolean input (‬‭


4 True‬‭or‬‭
False‬
‭) from the‬‭user and‬
‭print it.‬
i‭s_student = input("Are you a student? (True/False): ")‬
‭is_student = is_student.lower() == "true"‬
‭print(is_student)‬

‭5.Q. Convert a string input into an integer and print it.‬


‭ um_str = input("Enter a number: ")‬
n
‭num_int = int(num_str)‬
‭print(num_int)‬

‭6.‬‭Q. Convert an integer input into a float and print it.‬


‭ um = int(input("Enter an integer: "))‬
n
‭num_float = float(num)‬
‭print(num_float)‬

‭7.‬‭Q. Convert a float input into an integer and print‬‭it.‬


‭ ecimal_number = float(input("Enter a decimal number: "))‬
d
‭integer_number = int(decimal_number)‬
‭print(integer_number)‬

‭8.‬‭Q. Take two inputs in a single line and print them‬‭separately.‬


‭ , b = input("Enter two values: ").split()‬
a
‭print(a)‬
‭print(b)‬

‭9.Q. Take two integer inputs in a single line and print their sum.‬
‭ , b = map(int, input("Enter two integers: ").split())‬
a
‭sum_value = a + b‬
‭print(sum_value)‬

‭ 0.Q. Take three float inputs in a single line and print their‬
1
‭average.‬
‭x, y, z = map(float, input("Enter three float numbers: ").split())‬
‭ verage = (x + y + z) / 3‬
a
‭print(average)‬

‭Chapter 3 — if else / elif‬

‭Basic Logic:‬

‭In Python,‬
if‬
‭ else‬
‭,‬‭ elif‬‭are used to‬‭make decisions‬‭based‬‭on certain‬
‭, and‬‭
‭conditions.‬

‭●‬ ‭
if‬‭checks a condition. If it is‬‭True‬‭, the code inside it runs.‬

‭●‬ ‭
else‬‭runs when the‬‭
if‬‭condition is‬‭False‬‭.‬

‭●‬ ‭
elif‬‭(else if) checks‬‭another condition‬‭if the first‬‭
if‬‭is False.‬

‭Syntax:‬
‭if condition:‬
‭# code to run if condition is True‬
‭elif another_condition:‬
‭# code to run if first condition is False and this is True‬
‭else:‬
‭# code to run if all conditions are False‬

‭Simple Example:‬
‭age = int(input("Enter your age: "))‬

‭if age >= 18:‬


‭print("You are eligible to vote.")‬
‭else:‬
‭print("You are not eligible to vote.")‬

if‬
‭How‬‭ elif‬
‭,‬‭ else‬‭works:‬
‭,‬‭
if‬‭block‬‭:‬
‭1.‬‭

if‬‭condition first.‬
‭○‬ ‭Python checks the‬‭

‭○‬ I‭f it is True‬‭,‬


‭→ the code inside the‬‭ if‬‭block runs.‬
elif‬‭and‬‭
‭→ After that, Python‬‭skips‬‭all‬‭ else‬
‭.‬

elif‬‭block‬‭(short for "else if"):‬


‭2.‬‭

if‬‭condition was‬‭False‬‭, Python checks each‬‭


‭○‬ I‭f the‬‭ elif‬
‭one by one.‬

elif‬‭that is True‬‭will run its block.‬


‭○‬ ‭The‬‭first‬‭

‭○‬ O True‬‭condition is found, Python‬‭skips all the‬


‭ nce a‬‭
elif‬‭and‬‭
‭remaining‬‭ else‬ ‭.‬

else‬‭block‬‭:‬
‭3.‬‭

if‬‭and‬‭
‭○‬ I‭f‬‭none of the‬‭ elif‬‭conditions are True‬‭, then‬
else‬‭runs.‬

‭○‬ I‭t‬‭does not check any condition‬‭, it runs directly when all‬
‭previous checks fail.‬
‭Full Working Example + True Case Flow‬
‭marks = int(input("Enter your marks: "))‬

‭if marks >= 90:‬


‭print("Grade: A") # This runs if marks are 90 or more‬
‭elif marks >= 75:‬
‭print("Grade: B") # This runs if marks are between 75 and 89‬
‭elif marks >= 60:‬
‭print("Grade: C") # This runs if marks are between 60 and 74‬
‭elif marks >= 40:‬
‭print("Grade: D") # This runs if marks are between 40 and 59‬
‭else:‬
‭print("Grade: F") # This runs if marks are below 40‬

‭Example Walkthrough‬
I‭nput‬ ‭What Happens?‬
‭Marks‬
‭(say)‬
‭95‬ ‭f‬‭condition‬‭
i marks >= 90‬‭is True → prints "Grade:‬
‭A" → stops checking further‬
‭78‬ ‭f‬‭is False → checks first‬‭
i elif‬‭→‬‭
marks >= 75‬‭is‬
‭True → prints "Grade: B"‬
‭62‬ ‭f‬‭False → first‬‭
i elif‬‭False → second‬‭
elif‬‭
marks‬
>= 60‬‭True → prints "Grade: C"‬

‭45‬ elif‬‭
‭ ll previous False → third‬‭
A marks >= 40‬‭True‬
‭→ prints "Grade: D"‬
‭30‬ if‬‭and‬‭
‭ ll‬‭
A elif‬‭False → runs‬‭
else‬‭→ prints "Grade:‬
‭F"‬

‭Example using logical operators (‬‭


and‬ or‬
‭,‬‭ not‬
‭,‬‭ ‭):‬
‭ ge = int(input("Enter your age: "))‬
a
‭citizenship = input("Are you a citizen of this country? (yes/no): ")‬

‭if age >= 18 and citizenship.lower() == "yes":‬


‭print("You are eligible to vote.")‬
‭elif age >= 18 and citizenship.lower() == "no":‬
‭print("You are not eligible to vote because you are not a citizen.")‬
‭else:‬
‭print("You are not eligible to vote because you are under 18.")‬

‭Explanation:‬

‭●‬ ‭
and‬‭operator‬‭:‬

‭○‬ T
‭ he condition‬‭age >= 18 and citizenship.lower()‬
== "yes"‬‭means‬‭both conditions must be True‬‭for the‬

‭block to run.‬

‭○‬ F
‭ or example, a person aged 20 who is a citizen will enter‬
‭this block.‬

‭●‬ ‭
elif‬‭with‬‭
and‬
‭:‬

‭○‬ T
‭ he second‬‭ elif‬‭checks if‬‭age is >= 18‬‭but‬‭citizenship‬‭is‬
‭not "yes"‬‭(i.e., they are not a citizen). The block‬‭will‬
‭execute for a person aged 25 but not a citizen.‬

‭●‬ ‭
else‬
‭:‬

‭○‬ T
‭ he final block runs when neither condition is met (under‬
‭18 or non-citizen).‬

‭○‬ if‬
‭Example using Nested‬‭ ‭:‬
‭ ge = int(input("Enter your age: "))‬
a
‭income = float(input("Enter your monthly income: "))‬

‭if age >= 18:‬


‭if income >= 5000:‬
‭print("You are eligible for the loan.")‬
‭else:‬
‭print("You are not eligible for the loan due to low income.")‬
‭else:‬
‭print("You are not eligible for the loan because you are under 18.")‬

‭Explanation:‬

if‬
‭●‬ ‭First‬‭ ‭: It checks if the person is‬‭18 or older‬‭.‬

‭●‬ N
‭ ested‬‭if‬ if‬
‭: Inside the first‬‭ ‭, another check is done‬‭to see if‬
‭the‬‭monthly income is greater than or equal to 5000‬‭.‬

‭○‬ I‭f both conditions are met, the person is eligible for the‬
‭loan.‬

‭○‬ I‭f the income is below 5000, the person is not eligible due‬
‭to low income.‬
‭●‬ e
‭lse‬‭(outside the first‬‭
if‬
‭)‬‭: If the age is below 18, the loan is‬
‭not given because the person is too young.‬

‭ xample: Checking if a number is even or odd‬


E
‭using a ternary operator:‬

‭number = int(input("Enter a number: "))‬

‭ Ternary operator to check if the number is even or odd‬


#
‭result = "Even" if number % 2 == 0 else "Odd"‬

‭print(f"The number is {result}.")‬

‭Explanation:‬

‭●‬ T number % 2‬‭


‭ he‬‭ternary operator‬‭checks whether the‬‭ == 0‬
‭,‬
‭which determines if the number is even.‬

"Even"‬
‭○‬ ‭If‬‭True‬‭, it returns‬‭ ‭.‬

"Odd"‬
‭○‬ ‭If‬‭False‬‭, it returns‬‭ ‭.‬

‭●‬ T
‭ his is a concise way of doing a check that would otherwise‬
‭require an‬‭if-else‬‭block.‬

‭PROGRAMS‬

‭1. Check if a number is positive, negative, or zero:‬


‭number = int(input("Enter a number: "))‬

‭if number > 0:‬


‭print("The number is positive.")‬
‭elif number < 0:‬
‭print("The number is negative.")‬
‭else:‬
‭print("The number is zero.")‬

‭2. Check if a number is even or odd:‬


‭number = int(input("Enter a number: "))‬

‭if number % 2 == 0:‬


‭print("The number is even.")‬
‭else:‬
‭print("The number is odd.")‬

‭3. Find the largest of three numbers:‬


‭ = int(input("Enter first number: "))‬
a
‭b = int(input("Enter second number: "))‬
‭c = int(input("Enter third number: "))‬

‭if a >= b and a >= c:‬


‭print(f"The largest number is {a}.")‬
‭elif b >= a and b >= c:‬
‭print(f"The largest number is {b}.")‬
‭else:‬
‭print(f"The largest number is {c}.")‬

‭4. Check if a number is divisible by both 3 and 5:‬


‭number = int(input("Enter a number: "))‬
‭if number % 3 == 0 and number % 5 == 0:‬
‭print(f"{number} is divisible by both 3 and 5.")‬
‭else:‬
‭print(f"{number} is not divisible by both 3 and 5.")‬

‭5. Find the grade based on the score:‬


‭score = int(input("Enter your score: "))‬

‭if score >= 90:‬


‭print("You got an A.")‬
‭elif score >= 80:‬
‭print("You got a B.")‬
‭elif score >= 70:‬
‭print("You got a C.")‬
‭elif score >= 60:‬
‭print("You got a D.")‬
‭else:‬
‭print("You failed.")‬

‭6. Check if a number is within a range (1-100):‬


‭number = int(input("Enter a number: "))‬

‭if 1 <= number <= 100:‬


‭print("The number is within the range 1 to 100.")‬
‭else:‬
‭print("The number is out of the range 1 to 100.")‬

‭7. Check if a person is eligible to vote:‬


‭age = int(input("Enter your age: "))‬
‭if age >= 18:‬
‭print("You are eligible to vote.")‬
‭else:‬
‭print("You are not eligible to vote.")‬

‭8. Find whether a person is an adult, teenager, or child:‬


‭age = int(input("Enter your age: "))‬

‭if age >= 18:‬


‭print("You are an adult.")‬
‭elif age >= 13:‬
‭print("You are a teenager.")‬
‭else:‬
‭print("You are a child.")‬

‭9. Check if a number is a prime number:‬


‭num = int(input("Enter a number: "))‬

‭if num > 1:‬


‭for i in range(2, num):‬
‭if num % i == 0:‬
‭print(f"{num} is not a prime number.")‬
‭break‬
‭else:‬
‭print(f"{num} is a prime number.")‬
‭else:‬
‭print(f"{num} is not a prime number.")‬

‭10. Check if a number is a leap year:‬


‭year = int(input("Enter a 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.")‬

‭11. Check if a number is a palindrome:‬


‭num = input("Enter a number: ")‬

‭if num == num[::-1]:‬


‭print(f"{num} is a palindrome.")‬
‭else:‬
‭print(f"{num} is not a palindrome.")‬

‭12. Determine the largest of two numbers:‬


‭ = int(input("Enter first number: "))‬
a
‭b = int(input("Enter second number: "))‬

‭if a > b:‬


‭print(f"{a} is larger than {b}.")‬
‭elif b > a:‬
‭print(f"{b} is larger than {a}.")‬
‭else:‬
‭print("Both numbers are equal.")‬

‭13. Check if a character is a vowel or consonant:‬


‭char = input("Enter a character: ").lower()‬

‭if char in ['a', 'e', 'i', 'o', 'u']:‬


‭print(f"{char} is a vowel.")‬
‭else:‬
‭print(f"{char} is a consonant.")‬

if-elif-else‬
‭14. Check if a number is positive, negative, or zero using‬‭ ‭:‬
‭number = int(input("Enter a number: "))‬

‭if number > 0:‬


‭print("The number is positive.")‬
‭elif number < 0:‬
‭print("The number is negative.")‬
‭else:‬
‭print("The number is zero.")‬

‭15. Check if a person is eligible for a loan (age and income):‬


‭ ge = int(input("Enter your age: "))‬
a
‭income = float(input("Enter your monthly income: "))‬

‭if age >= 18 and income >= 5000:‬


‭print("You are eligible for the loan.")‬
‭else:‬
‭print("You are not eligible for the loan.")‬

‭16. Determine if a year is a century year:‬


‭year = int(input("Enter a year: "))‬

‭if year % 100 == 0:‬


‭print(f"{year} is a century year.")‬
‭else:‬
‭print(f"{year} is not a century year.")‬

‭17. Calculate the discount on a product based on the price:‬


‭price = float(input("Enter the price of the product: "))‬

‭if price > 1000:‬


‭discount = 0.1 * price‬
‭elif price > 500:‬
‭discount = 0.05 * price‬
‭else:‬
‭discount = 0‬

‭print(f"Discount on the product is: {discount}")‬

‭18. Check if a string is a palindrome:‬


‭text = input("Enter a text: ")‬

‭if text == text[::-1]:‬


‭print(f"{text} is a palindrome.")‬
‭else:‬
‭print(f"{text} is not a palindrome.")‬

‭19. Check if a number is divisible by 4 but not by 6:‬


‭num = int(input("Enter a number: "))‬

‭if num % 4 == 0 and num % 6 != 0:‬


‭print(f"{num} is divisible by 4 but not by 6.")‬
‭else:‬
‭print(f"{num} is either not divisible by 4 or divisible by 6.")‬

‭20. Check if a number is in a given range (e.g., 50-100):‬


‭num = int(input("Enter a number: "))‬

‭if 50 <= num <= 100:‬


‭ rint(f"{num} is within the range 50-100.")‬
p
‭else:‬
‭print(f"{num} is outside the range 50-100.")‬

‭—------------------------------------------------------------------------------------------‬

‭Chapter 4 — Loops‬
‭Definition:‬
‭ ‬‭loop‬‭is a structure that repeats a block of code multiple times until a‬
A
‭certain condition is satisfied.‬
‭Loops help avoid writing the same code again and again manually.‬

‭Types of Loops in Python:‬


‭●‬ ‭while loop‬

‭●‬ ‭for loop‬

‭1. while loop‬


‭Algorithm:‬

‭●‬ ‭Step 1: Initialize the variable(s).‬

‭●‬ ‭Step 2: Check the condition.‬

‭●‬ ‭Step 3: If the condition is‬‭True‬‭, execute the loop‬‭body.‬


‭●‬ ‭Step 4: Update the variable(s).‬

‭●‬ ‭Step 5: Repeat steps 2-4 until the condition becomes‬‭False‬‭.‬

‭Example:‬
i‭ = 1‬
‭while i <= 5:‬
‭print(i)‬
‭i = i + 1‬

‭Detailed Execution:‬

1 <= 5‬‭→ True → Print‬‭


‭●‬ ‭i = 1‬‭→ Condition‬‭ 1‬‭→ Update‬‭i to‬‭
2‬

2 <= 5‬‭→ True → Print‬‭


‭●‬ ‭i = 2‬‭→ Condition‬‭ 2‬‭→ Update‬‭i to‬‭
3‬

3 <= 5‬‭→ True → Print‬‭


‭●‬ ‭i = 3‬‭→ Condition‬‭ 3‬‭→ Update‬‭i to‬‭
4‬

4 <= 5‬‭→ True → Print‬‭


‭●‬ ‭i = 4‬‭→ Condition‬‭ 4‬‭→ Update‬‭i to‬‭
5‬

5 <= 5‬‭→ True → Print‬‭


‭●‬ ‭i = 5‬‭→ Condition‬‭ 5‬‭→ Update‬‭i to‬‭
6‬

6 <= 5‬‭→ False → Loop stops.‬


‭●‬ ‭i = 6‬‭→ Condition‬‭

‭Final Output:‬
‭‬
1
‭2‬
‭‬
3
‭4‬
‭5‬

‭2. for loop‬


‭Algorithm:‬

‭●‬ ‭Step 1: Take a sequence like a list, string, or range.‬

‭●‬ ‭Step 2: Pick each item one by one.‬

‭●‬ ‭Step 3: Execute the loop body for each item.‬

‭●‬ S
‭ tep 4: Automatically moves to the next item until the sequence‬
‭ends.‬

‭Example:‬
‭for i in range(1, 6):‬
‭print(i)‬

‭Detailed Execution:‬

1‬
‭●‬ ‭i = 1‬‭→ Print‬‭

2‬
‭●‬ ‭i = 2‬‭→ Print‬‭
3‬
‭●‬ ‭i = 3‬‭→ Print‬‭

4‬
‭●‬ ‭i = 4‬‭→ Print‬‭

5‬
‭●‬ ‭i = 5‬‭→ Print‬‭

‭●‬ ‭Sequence ends → Loop stops.‬

‭Final Output:‬
‭‬
1
‭2‬
‭3‬
‭4‬
‭5‬

‭Break Statement‬
‭Meaning:‬
‭●‬ T break‬‭statement is used to‬‭immediately stop‬‭the‬‭loop,‬
‭ he‬‭
‭even if the condition is still true.‬

‭●‬ ‭It‬‭exits‬‭the loop completely when a certain condition is met.‬

‭Example:‬
i‭ = 1‬
‭while i <= 5:‬
‭if i == 3:‬
‭break‬
‭print(i)‬
‭i = i + 1‬

‭Detailed Execution:‬

1 <= 5‬‭→ True →‬‭


‭●‬ i‭ = 1‬‭→‬‭ i == 3‬‭→ False → Print‬‭
1‬‭→‬
2‬
‭Update i to‬‭

2 <= 5‬‭→ True →‬‭


‭●‬ i‭ = 2‬‭→‬‭ i == 3‬‭→ False → Print‬‭
2‬‭→‬
3‬
‭Update i to‬‭

3 <= 5‬‭→ True →‬‭


‭●‬ i‭ = 3‬‭→‬‭ i == 3‬‭→ True →‬‭Break happens‬
‭→ Loop stops immediately.‬

‭Final Output:‬
‭‬
1
‭2‬

‭Continue Statement‬
‭Meaning:‬
‭●‬ T
‭ he‬‭continue‬‭statement is used to‬‭skip the current‬‭iteration‬
‭and‬‭jump to the next‬‭iteration of the loop.‬
‭●‬ I‭t does not stop the loop, only skips the remaining code for that‬
‭particular cycle.‬

‭Example:‬
i‭ = 0‬
‭while i < 5:‬
‭i = i + 1‬
‭if i == 3:‬
‭continue‬
‭print(i)‬

‭Detailed Execution:‬

1‬‭→‬‭
‭●‬ ‭i = 0‬‭→ Update i to‬‭ 1 < 5‬‭→‬‭
i == 3‬‭→ False → Print‬‭
1‬

2‬‭→‬‭
‭●‬ ‭i = 1‬‭→ Update i to‬‭ 2 < 5‬‭→‬‭
i == 3‬‭→ False → Print‬‭
2‬

3‬‭→‬‭
‭●‬ i‭ = 2‬‭→ Update i to‬‭ 3 < 5‬‭→‬‭
i == 3‬‭→ True →‬‭Continue‬
‭happens‬‭→ Skips printing → Next cycle‬

4‬‭→‬‭
‭●‬ ‭i = 3‬‭→ Update i to‬‭ 4 < 5‬‭→‬‭
i == 3‬‭→ False → Print‬‭
4‬

5‬‭→‬‭
‭●‬ ‭i = 4‬‭→ Update i to‬‭ 5 < 5‬‭→ False → Loop stops.‬

‭Final Output:‬
‭‬
1
‭2‬
‭4‬
‭5‬
3‬‭is skipped because of‬‭
‭(Note:‬‭ continue‬
‭.)‬

‭Indentation in Python‬
‭Meaning:‬
‭●‬ I‭ndentation‬‭means‬‭adding spaces‬‭or‬‭tabs‬‭at the beginning of a‬
‭line.‬

‭●‬ I‭n Python,‬‭indentation is compulsory‬‭to define‬‭which‬


‭statements belong inside a loop, if-else block, function, etc.‬

‭●‬ ‭If indentation is wrong or missing, Python will show an‬‭error‬‭.‬

‭Important Points:‬
‭●‬ ‭Indentation is usually‬‭4 spaces‬‭.‬

‭●‬ A
‭ ll the statements inside a block (like loop, if-else) must be‬
‭indented equally‬‭.‬

‭●‬ W
‭ ithout proper indentation,‬‭Python doesn't know which‬‭lines‬
‭are part of the block‬‭.‬
‭Example:‬
i‭ = 1‬
‭while i <= 3:‬
‭print(i)‬
‭i = i + 1‬

‭Detailed Execution:‬

1 <= 3‬‭→ True → Indented lines (print and i = i+1) are‬


‭●‬ i‭ = 1‬‭→‬‭
‭executed.‬

2 <= 3‬‭→ True → Indented lines executed again.‬


‭●‬ ‭i = 2‬‭→‬‭

3 <= 3‬‭→ True → Indented lines executed again.‬


‭●‬ ‭i = 3‬‭→‬‭

4 <= 3‬‭→ False → Loop stops.‬


‭●‬ ‭i = 4‬‭→‬‭

‭Final Output:‬
‭‬
1
‭2‬
‭3‬

‭If indentation was wrong:‬


‭Example of wrong indentation:‬
‭i = 1‬
‭ hile i <= 3:‬
w
‭print(i) # Error here!‬
‭i = i + 1‬

‭●‬ P print(i)‬
‭ ython will show an‬‭IndentationError‬‭because the‬‭
‭line is‬‭not indented‬‭properly.‬

while i <= 3:‬


‭●‬ ‭It expects an‬‭indent‬‭after‬‭ ‭.‬

‭●‬ ‭Nested Loops‬


‭Meaning:‬
‭●‬ ‭A‬‭nested loop‬‭means a‬‭loop inside another loop‬‭.‬

‭●‬ T
‭ he‬‭inner loop‬‭runs completely for every‬‭single repetition‬‭of‬
‭the‬‭outer loop‬‭.‬

‭●‬ U
‭ seful when we work with‬‭patterns‬‭,‬‭tables‬‭,‬‭multi-level data‬‭,‬
‭etc.‬

‭Working Logic:‬
‭ uter loop starts ➔ inner loop runs‬‭fully‬‭➔ then outer‬‭loop‬
‭●‬ O
‭moves to next iteration ➔ inner loop runs fully again ➔ and so‬
‭on.‬

‭Example:‬
i‭ = 1‬
‭while i <= 3:‬
‭j = 1‬
‭while j <= 2:‬
‭print(i, j)‬
‭j = j + 1‬
‭i = i + 1‬

‭Detailed Execution:‬
‭●‬ ‭i = 1‬‭:‬

1 <= 2‬‭→ True → Print‬‭


‭○‬ ‭j = 1‬‭→‬‭ 1 1‬‭→ j = 2‬

2 <= 2‬‭→ True → Print‬‭


‭○‬ ‭j = 2‬‭→‬‭ 1 2‬‭→ j = 3‬

3 <= 2‬‭→ False → Inner loop ends.‬


‭○‬ ‭j = 3‬‭→‬‭

‭●‬ ‭i = 2‬‭:‬

1 <= 2‬‭→ True → Print‬‭


‭○‬ ‭j = 1‬‭→‬‭ 2 1‬‭→ j = 2‬

2 <= 2‬‭→ True → Print‬‭


‭○‬ ‭j = 2‬‭→‬‭ 2 2‬‭→ j = 3‬

3 <= 2‬‭→ False → Inner loop ends.‬


‭○‬ ‭j = 3‬‭→‬‭

‭●‬ ‭i = 3‬‭:‬

1 <= 2‬‭→ True → Print‬‭


‭○‬ ‭j = 1‬‭→‬‭ 3 1‬‭→ j = 2‬

2 <= 2‬‭→ True → Print‬‭


‭○‬ ‭j = 2‬‭→‬‭ 3 2‬‭→ j = 3‬
3 <= 2‬‭→ False → Inner loop ends.‬
‭○‬ ‭j = 3‬‭→‬‭

4 <= 3‬‭→ False → Outer loop ends.‬


‭●‬ ‭i = 4‬‭→‬‭

‭Final Output:‬
‭ 1‬
1
‭1 2‬
‭2 1‬
‭2 2‬
‭3 1‬
‭3 2‬

‭PROGRAMS‬
‭1. Print numbers from 1 to 5 using while loop‬
i‭ = 1‬
‭while i <= 5:‬
‭print(i)‬
‭i = i + 1‬

‭2. Print numbers from 1 to 5 using for loop‬


‭for i in range(1, 6):‬
‭print(i)‬

‭3. Print even numbers from 2 to 10‬


‭i = 2‬
‭while i <= 10:‬
‭print(i)‬
‭i = i + 2‬

‭ . Print first 5 natural numbers, but stop if number is 3 (break‬


4
‭statement)‬
i‭ = 1‬
‭while i <= 5:‬
‭if i == 3:‬
‭break‬
‭print(i)‬
‭i = i + 1‬

‭5. Print numbers from 1 to 5, skip 3 (continue statement)‬


i‭ = 0‬
‭while i < 5:‬
‭i = i + 1‬
‭if i == 3:‬
‭continue‬
‭print(i)‬

‭6. Sum of numbers from 1 to 5‬


i‭ = 1‬
‭sum = 0‬
‭while i <= 5:‬
‭sum = sum + i‬
‭i = i + 1‬
‭print("Sum:", sum)‬
‭7. Display multiplication table of 2‬
i‭ = 1‬
‭while i <= 10:‬
‭print("2 x", i, "=", 2*i)‬
‭i = i + 1‬

‭8. Nested loop to print pair (i, j)‬

i‭ = 1‬
‭while i <= 2:‬
‭j = 1‬
‭while j <= 3:‬
‭print(i, j)‬
‭j = j + 1‬
‭i = i + 1‬

‭9. Print pattern:‬


*‭ ‬
‭* *‬
‭* * *‬

i‭ = 1‬
‭while i <= 3:‬
‭j = 1‬
‭while j <= i:‬
‭print('*', end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i + 1‬
‭ 0. Check if a number is positive or negative (with while loop‬
1
‭once)‬
‭ um = int(input("Enter a number: "))‬
n
‭while True:‬
‭if num >= 0:‬
‭print("Positive number")‬
‭else:‬
‭print("Negative number")‬
‭break‬

‭11. Right-Angle Triangle of Numbers‬


‭Output:‬
‭‬
1
‭1 2‬
‭1 2 3‬
‭1 2 3 4‬

i‭ = 1‬
‭while i <= 4:‬
‭j = 1‬
‭while j <= i:‬
‭print(j, end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i + 1‬

‭12. Inverted Right-Angle Triangle of Numbers‬


‭Output:‬
‭ 2 3 4‬
1
‭1 2 3‬
‭1 2‬
‭1‬
i‭ = 4‬
‭while i >= 1:‬
‭j = 1‬
‭while j <= i:‬
‭print(j, end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i - 1‬

‭13. Star Pyramid Pattern‬


‭Output:‬
*‭ ‬
‭* *‬
‭* * *‬
‭* * * *‬

i‭ = 1‬
‭while i <= 4:‬
‭space = 4 - i‬
‭while space > 0:‬
‭print(' ', end=' ')‬
‭space = space - 1‬
‭j = 1‬
‭while j <= i:‬
‭print('*', end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i + 1‬

‭14. Inverted Star Pyramid Pattern‬


‭Output:‬
‭* * * *‬
‭* * *‬
‭* *‬
‭*‬

i‭ = 4‬
‭while i >= 1:‬
‭space = 4 - i‬
‭while space > 0:‬
‭print(' ', end=' ')‬
‭space = space - 1‬
‭j = 1‬
‭while j <= i:‬
‭print('*', end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i - 1‬

‭15. Full Pyramid of Numbers‬


‭Output:‬
‭‬
1
‭1 2‬
‭1 2 3‬
‭1 2 3 4‬

i‭ = 1‬
‭while i <= 4:‬
‭space = 4 - i‬
‭while space > 0:‬
‭print(' ', end=' ')‬
‭space = space - 1‬
‭j = 1‬
‭while j <= i:‬
‭print(j, end=' ')‬
‭j = j + 1‬
‭ rint()‬
p
‭i = i + 1‬

‭16. Number Diamond Pattern‬


‭Output:‬

‭‬
1
‭1 2‬
‭1 2 3‬
‭1 2 3 4‬
‭1 2 3‬
‭1 2‬
‭1‬

i‭ = 1‬
‭while i <= 4:‬
‭space = 4 - i‬
‭while space > 0:‬
‭print(' ', end=' ')‬
‭space = space - 1‬
‭j = 1‬
‭while j <= i:‬
‭print(j, end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i + 1‬

i‭ = 3‬
‭while i >= 1:‬
‭space = 4 - i‬
‭while space > 0:‬
‭print(' ', end=' ')‬
‭space = space - 1‬
j‭ = 1‬
‭while j <= i:‬
‭print(j, end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i - 1‬

‭17. Half Pyramid of Stars (Same Number)‬


‭Output:‬
‭‬
1
‭2 2‬
‭3 3 3‬
‭4 4 4 4‬

i‭ = 1‬
‭while i <= 4:‬
‭j = 1‬
‭while j <= i:‬
‭print(i, end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i + 1‬

‭18. Inverted Half Pyramid of Stars (Same Number)‬


‭Output:‬
‭ 4 4 4‬
4
‭3 3 3‬
‭2 2‬
‭1‬

i‭ = 4‬
‭while i >= 1:‬
j‭ = 1‬
‭while j <= i:‬
‭print(i, end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i - 1‬

‭19. Diamond Pattern with Stars‬


‭Output:‬
*‭ ‬
‭* *‬
‭* * *‬
‭* * * *‬
‭* * *‬
‭* *‬
‭*‬

i‭ = 1‬
‭while i <= 4:‬
‭space = 4 - i‬
‭while space > 0:‬
‭print(' ', end=' ')‬
‭space = space - 1‬
‭j = 1‬
‭while j <= i:‬
‭print('*', end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i + 1‬

i‭ = 3‬
‭while i >= 1:‬
‭space = 4 - i‬
‭while space > 0:‬
‭print(' ', end=' ')‬
‭ pace = space - 1‬
s
‭j = 1‬
‭while j <= i:‬
‭print('*', end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i - 1‬

‭20. Half Inverted Pyramid of Numbers‬


‭Output:‬
‭1 2 3 4‬
‭1 2 3‬
‭1 2‬
‭1‬

i‭ = 4‬
‭while i >= 1:‬
‭space = 4 - i‬
‭while space > 0:‬
‭print(' ', end=' ')‬
‭space = space - 1‬
‭j = 1‬
‭while j <= i:‬
‭print(j, end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i - 1‬

‭21. Alphabet Right-Angle Triangle Pattern‬


‭Output:‬
‭‬
A
‭A B‬
‭ B C‬
A
‭A B C D‬

i‭ = 1‬
‭while i <= 4:‬
‭j = 1‬
‭while j <= i:‬
‭print(chr(64 + j), end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i + 1‬

‭22. Inverted Alphabet Right-Angle Triangle Pattern‬


‭Output:‬
‭ B C D‬
A
‭A B C‬
‭A B‬
‭A‬

i‭ = 4‬
‭while i >= 1:‬
‭j = 1‬
‭while j <= i:‬
‭print(chr(64 + j), end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i - 1‬

‭23. Alphabet Pyramid Pattern‬


‭Output:‬
‭‬
A
‭A B‬
‭ B C‬
A
‭A B C D‬

i‭ = 1‬
‭while i <= 4:‬
‭space = 4 - i‬
‭while space > 0:‬
‭print(' ', end=' ')‬
‭space = space - 1‬
‭j = 1‬
‭while j <= i:‬
‭print(chr(64 + j), end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i + 1‬

‭24. Inverted Alphabet Pyramid Pattern‬


‭Output:‬
‭A B C D‬
‭A B C‬
‭A B‬
‭A‬

i‭ = 4‬
‭while i >= 1:‬
‭space = 4 - i‬
‭while space > 0:‬
‭print(' ', end=' ')‬
‭space = space - 1‬
‭j = 1‬
‭while j <= i:‬
‭print(chr(64 + j), end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i - 1‬
‭ 5. Diamond Pattern of Alphabets‬
2
‭Output:‬
‭‬
A
‭A B‬
‭A B C‬
‭A B C D‬
‭A B C‬
‭A B‬
‭A‬

i‭ = 1‬
‭while i <= 4:‬
‭space = 4 - i‬
‭while space > 0:‬
‭print(' ', end=' ')‬
‭space = space - 1‬
‭j = 1‬
‭while j <= i:‬
‭print(chr(64 + j), end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i + 1‬

i‭ = 3‬
‭while i >= 1:‬
‭space = 4 - i‬
‭while space > 0:‬
‭print(' ', end=' ')‬
‭space = space - 1‬
‭j = 1‬
‭while j <= i:‬
‭print(chr(64 + j), end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i - 1‬

‭26. Alphabet Reverse Pyramid Pattern‬


‭Output:‬
‭D C B A‬
‭C B A‬
‭B A‬
‭A‬

i‭ = 4‬
‭while i >= 1:‬
‭space = 4 - i‬
‭while space > 0:‬
‭print(' ', end=' ')‬
‭space = space - 1‬
‭j = i‬
‭while j >= 1:‬
‭print(chr(64 + j), end=' ')‬
‭j = j - 1‬
‭print()‬
‭i = i - 1‬

‭27. Alphabet Number Pattern‬


‭Output:‬
‭‬
A
‭B B‬
‭C C C‬
‭D D D D‬

i‭ = 1‬
‭while i <= 4:‬
‭j = 1‬
‭while j <= i:‬
‭ rint(chr(64 + i), end=' ')‬
p
‭j = j + 1‬
‭print()‬
‭i = i + 1‬

‭28. Alphabet Left-Angle Triangle‬


‭Output:‬
‭‬
A
‭B B‬
‭C C C‬
‭D D D D‬

i‭ = 1‬
‭while i <= 4:‬
‭j = 1‬
‭while j <= i:‬
‭print(chr(64 + i), end=' ')‬
‭j = j + 1‬
‭print()‬
‭i = i + 1‬

‭ 9. Write a Python program to print the Fibonacci series up to a‬


2
‭given number of terms.‬
‭Output:‬
‭ nter the number of terms: 10‬
E
‭0 1 1 2 3 5 8 13 21 34‬

‭ = int(input("Enter the number of terms: "))‬


n
‭a, b = 0, 1‬
‭print(a, end=' ')‬
‭for _ in range(n - 1):‬
‭print(b, end=' ')‬
‭a, b = b, a + b‬

‭ 0. Write a Python program to check whether a given number is‬


3
‭an Armstrong number or not.‬
‭Output:‬
‭ nter a number: 153‬
E
‭153 is an Armstrong number‬

‭ um = int(input("Enter a number: "))‬


n
‭sum = 0‬
‭temp = num‬
‭while temp > 0:‬
‭digit = temp % 10‬
‭sum += digit ** 3‬
‭temp //= 10‬
‭if sum == num:‬
‭print(f"{num} is an Armstrong number")‬
‭else:‬
‭print(f"{num} is not an Armstrong number")‬

‭ 1. Write a Python program to check whether a given number is a‬


3
‭prime number or not.‬
‭Output:‬
‭ nter a number: 17‬
E
‭17 is a prime number‬

‭ um = int(input("Enter a number: "))‬


n
‭is_prime = True‬
‭for i in range(2, num):‬
‭if num % i == 0:‬
‭is_prime = False‬
‭ reak‬
b
‭if is_prime and num > 1:‬
‭print(f"{num} is a prime number")‬
‭else:‬
‭print(f"{num} is not a prime number")‬

‭32. Write a Python program to calculate the factorial of a number.‬


‭Output:‬
‭ nter a number: 5‬
E
‭Factorial of 5 is 120‬

‭ um = int(input("Enter a number: "))‬


n
‭fact = 1‬
‭for i in range(1, num + 1):‬
‭fact *= i‬
‭print(f"Factorial of {num} is {fact}")‬

‭ 3. Write a Python program to find the sum of digits of a given‬


3
‭number.‬
‭Output:‬
‭ nter a number: 123‬
E
‭Sum of digits of 123 is 6‬

‭ um = int(input("Enter a number: "))‬


n
‭sum_of_digits = 0‬
‭while num > 0:‬
‭sum_of_digits += num % 10‬
‭num //= 10‬
‭print(f"Sum of digits is {sum_of_digits}")‬
‭34. Write a Python program to reverse a given number.‬
‭Output:‬
‭ nter a number: 12345‬
E
‭Reverse of 12345 is 54321‬

‭ um = int(input("Enter a number: "))‬


n
‭reverse = 0‬
‭while num > 0:‬
‭reverse = reverse * 10 + num % 10‬
‭num //= 10‬
‭print(f"Reverse of the number is {reverse}")‬

‭ 5. Write a Python program to check if a given number is a‬


3
‭palindrome.‬
‭Output:‬
‭ nter a number: 121‬
E
‭121 is a palindrome‬

‭ um = int(input("Enter a number: "))‬


n
‭temp = num‬
‭reverse = 0‬
‭while temp > 0:‬
‭reverse = reverse * 10 + temp % 10‬
‭temp //= 10‬
‭if reverse == num:‬
‭print(f"{num} is a palindrome")‬
‭else:‬
‭print(f"{num} is not a palindrome")‬
‭ 6. Write a Python program to check whether a given number is a‬
3
‭perfect number or not.‬
‭Output:‬
‭ nter a number: 28‬
E
‭28 is a perfect number‬

‭ um = int(input("Enter a number: "))‬


n
‭sum_of_divisors = 0‬
‭for i in range(1, num):‬
‭if num % i == 0:‬
‭sum_of_divisors += i‬
‭if sum_of_divisors == num:‬
‭print(f"{num} is a perfect number")‬
‭else:‬
‭print(f"{num} is not a perfect number")‬

‭ 7. Write a Python program to calculate the sum of natural‬


3
‭numbers up to a given number.‬
‭Output:‬
‭ nter a number: 10‬
E
‭Sum of natural numbers up to 10 is 55‬

‭ um = int(input("Enter a number: "))‬


n
‭sum_of_natural_numbers = num * (num + 1) // 2‬
‭print(f"Sum of natural numbers up to {num} is‬
‭{sum_of_natural_numbers}")‬

‭ 8. Write a Python program to calculate the sum of even and odd‬


3
‭numbers separately in a given range.‬
‭Output:‬
‭ nter the range: 10‬
E
‭Sum of even numbers is 30‬
‭Sum of odd numbers is 25‬

‭ um = int(input("Enter the range: "))‬


n
‭even_sum = 0‬
‭odd_sum = 0‬
‭for i in range(1, num + 1):‬
‭if i % 2 == 0:‬
‭even_sum += i‬
‭else:‬
‭odd_sum += i‬
‭print(f"Sum of even numbers is {even_sum}")‬
‭print(f"Sum of odd numbers is {odd_sum}")‬

‭ 9. Write a Python program to count the number of digits in a‬


3
‭given number.‬
‭Output:‬
‭ nter a number: 12345‬
E
‭Number of digits in 12345 is 5‬

‭ um = int(input("Enter a number: "))‬


n
‭count = 0‬
‭while num > 0:‬
‭count += 1‬
‭num //= 10‬
‭print(f"Number of digits is {count}")‬

‭ 0. Write a Python program to find the Greatest Common Divisor‬


4
‭(GCD) of two numbers.‬
‭Output:‬
‭ nter two numbers: 24 36‬
E
‭GCD of 24 and 36 is 12‬

‭ = int(input("Enter first number: "))‬


a
‭b = int(input("Enter second number: "))‬
‭while b:‬
‭a, b = b, a % b‬
‭print(f"GCD is {a}")‬

‭ 1. Write a Python program to find the Least Common Multiple‬


4
‭(LCM) of two numbers.‬
‭Output:‬
‭ nter two numbers: 4 6‬
E
‭LCM of 4 and 6 is 12‬

‭ = int(input("Enter first number: "))‬


a
‭b = int(input("Enter second number: "))‬
‭lcm = (a * b) // gcd(a, b)‬
‭print(f"LCM is {lcm}")‬

‭ 2. Write a Python program to check if a given number is an‬


4
‭Armstrong number for N digits.‬
‭Output:‬
‭ nter a number: 153‬
E
‭153 is an Armstrong number‬

‭ um = int(input("Enter a number: "))‬


n
‭num_digits = len(str(num))‬
‭sum_of_powers = 0‬
‭temp = num‬
‭while temp > 0:‬
‭ igit = temp % 10‬
d
‭sum_of_powers += digit ** num_digits‬
‭temp //= 10‬
‭if sum_of_powers == num:‬
‭print(f"{num} is an Armstrong number")‬
‭else:‬
‭print(f"{num} is not an Armstrong number")‬

‭ 3. Write a Python program to calculate the sum of digits of a‬


4
‭number using recursion.‬
‭Output:‬
‭ nter a number: 123‬
E
‭Sum of digits of 123 is 6‬

‭def sum_of_digits(num):‬
‭if num == 0:‬
‭return 0‬
‭else:‬
‭return num % 10 + sum_of_digits(num // 10)‬

‭ um = int(input("Enter a number: "))‬


n
‭print(f"Sum of digits is {sum_of_digits(num)}")‬

‭ 4. Write a Python program to check if a given number is a‬


4
‭perfect square.‬
‭Output:‬
‭ nter a number: 16‬
E
‭16 is a perfect square‬

‭import math‬
‭ um = int(input("Enter a number: "))‬
n
‭sqrt = int(math.sqrt(num))‬
‭if sqrt * sqrt == num:‬
‭print(f"{num} is a perfect square")‬
‭else:‬
‭print(f"{num} is not a perfect square")‬

‭ 5. Write a Python program to find the HCF (Highest Common‬


4
‭Factor) of two numbers using functions.‬
‭Output:‬
‭ nter two numbers: 36 60‬
E
‭HCF of 36 and 60 is 12‬

‭def hcf(a, b):‬


‭while b:‬
‭a, b = b, a % b‬
‭return a‬

‭ um1 = int(input("Enter first number: "))‬


n
‭num2 = int(input("Enter second number: "))‬
‭print(f"HCF is {hcf(num1, num2)}")‬

‭ 6. Write a Python program to find the LCM (Least Common‬


4
‭Multiple) of two numbers using functions.‬
‭Output:‬
‭ nter two numbers: 4 6‬
E
‭LCM of 4 and 6 is 12‬

‭def lcm(a, b):‬


‭return (a * b) // hcf(a, b)‬
‭def hcf(a, b):‬
‭while b:‬
‭a, b = b, a % b‬
‭return a‬

‭ um1 = int(input("Enter first number: "))‬


n
‭num2 = int(input("Enter second number: "))‬
‭print(f"LCM is {lcm(num1, num2)}")‬

‭ 7. Write a Python program to print the multiplication table for a‬


4
‭number.‬
‭Output:‬
‭ nter a number: 5‬
E
‭Multiplication table of 5:‬
‭5 10 15 20 25 30 35 40 45 50‬

‭ um = int(input("Enter a number: "))‬


n
‭for i in range(1, 11):‬
‭print(num * i, end=' ')‬
‭Chapter 5: List‬
‭1. Definition:‬

‭ ‬‭list‬‭in Python is an ordered collection of elements.‬‭Lists are‬


A
‭mutable‬‭, which means they can be changed after creation.‬‭Lists are‬
‭used to store multiple items in a single variable.‬
‭2. Declaration:‬

[]‬
I‭n Python, you can declare a list using square brackets‬‭ ‭, and‬
‭elements inside the list are separated by commas.‬
‭Syntax:‬
‭list_name = [item1, item2, item3, ...]‬

‭Example:‬
‭fruits = ["apple", "banana", "cherry"]‬

‭3. Indexing in Lists:‬

‭ ists in Python are‬‭indexed‬‭starting from‬‭0‬‭for the‬‭first element. You‬


L
‭can access the elements of a list using their‬‭index‬‭.‬‭Python also‬
‭supports‬‭negative indexing‬‭, where‬‭-1‬‭refers to the last element,‬‭ -2‬
‭refers to the second-last element, and so on.‬
‭Indexing Syntax:‬
‭list_name[index]‬

‭Example:‬
‭fruits = ["apple", "banana", "cherry"]‬

‭ Accessing by positive index‬


#
‭print(fruits[0]) # Output: apple‬
‭print(fruits[1]) # Output: banana‬

‭ Accessing by negative index‬


#
‭print(fruits[-1]) # Output: cherry‬
‭print(fruits[-2]) # Output: banana‬

‭Explanation of Indexing:‬

‭●‬ ‭
fruits[0]‬ "apple"‬
‭: This refers to the first element, which is‬‭ ‭.‬

‭●‬ f
‭ruits[1]‬ ‭: This refers to the second element, which‬‭is‬
"banana"‬
‭ ‭.‬

‭●‬ f
‭ruits[-1]‬ ‭: This refers to the last element, which‬‭is‬
"cherry"‬
‭ ‭.‬

‭●‬ f
‭ruits[-2]‬ ‭: This refers to the second-last element,‬‭which is‬
"banana"‬
‭ ‭.‬

‭1. Accessing an Element from the List and Printing Using Index:‬
‭ Initial list‬
#
‭fruits = ["apple", "banana", "cherry"]‬

‭ Accessing and printing the element at index 1‬


#
‭print(fruits[1]) # Output: banana‬
‭ xplanation‬‭: This directly accesses the element at index 1 in the list‬
E
fruits‬
‭ "banana"‬
‭, which is‬‭ ‭.‬

‭2. Taking User Input to Access and Print an Element by Index:‬


‭ Initial list‬
#
‭fruits = ["apple", "banana", "cherry"]‬

‭ Taking user input to access an element‬


#
‭index_to_access = int(input("Enter index (0, 1, or 2) to access a fruit:‬
‭"))‬
‭print(f"The element at index {index_to_access} is:‬
‭{fruits[index_to_access]}")‬

‭ xplanation‬‭: The user is asked to input an index, and the program‬


E
‭prints the element from the list at that index.‬

‭3. Taking User Input to Store a Value in the List and Print the Updated List:‬
‭ Initial list‬
#
‭fruits = ["apple", "banana", "cherry"]‬

‭ Taking user input to update the list‬


#
‭index_to_update = int(input("Enter index (0, 1, or 2) to insert a new‬
‭fruit: "))‬
‭new_fruit = input("Enter the name of the fruit you want to insert: ")‬

‭ Updating the list at the specified index‬


#
‭fruits[index_to_update] = new_fruit‬

‭ Print the updated list‬


#
‭print(f"Updated list: {fruits}")‬
‭ xplanation‬‭: The user provides an index and a new fruit name, which‬
E
‭is inserted into the list at the specified index, and the updated list is‬
‭printed.‬

‭ ist of commonly used list functions/methods‬‭in Python,‬


L
‭explained with‬‭simple examples‬‭:‬

append()‬
‭1.‬‭

‭Adds an element at the end of the list.‬


‭fruits = ['apple', 'banana']‬
‭fruits.append('orange')‬
‭print(fruits) # ['apple', 'banana', 'orange']‬

insert(index, element)‬
‭2.‬‭

‭Inserts an element at a specific index.‬


‭fruits = ['apple', 'banana']‬
‭fruits.insert(1, 'cherry')‬
‭print(fruits) # ['apple', 'cherry', 'banana']‬

extend(iterable)‬
‭3.‬‭

‭Adds all elements from another list (or iterable).‬


‭a = [1, 2]‬
‭b = [3, 4]‬
‭a.extend(b)‬
‭print(a) # [1, 2, 3, 4]‬

remove(value)‬
‭4.‬‭

‭Removes the first occurrence of a value.‬


‭nums = [1, 2, 3, 2]‬
‭nums.remove(2)‬
‭print(nums) # [1, 3, 2]‬

pop(index)‬
‭5.‬‭

‭Removes and returns the element at the given index.‬


‭If no index is given, removes the last element.‬
‭nums = [10, 20, 30]‬
‭nums.pop(1)‬
‭print(nums) # [10, 30]‬

clear()‬
‭6.‬‭
‭Removes all elements from the list.‬
‭nums = [1, 2, 3]‬
‭nums.clear()‬
‭print(nums) # []‬

index(value)‬
‭7.‬‭

‭Returns the index of the first occurrence of the value.‬


‭nums = [5, 10, 15]‬
‭print(nums.index(10)) # 1‬

count(value)‬
‭8.‬‭

‭Counts how many times a value appears.‬


‭nums = [1, 2, 2, 3]‬
‭print(nums.count(2)) # 2‬

sort()‬
‭9.‬‭

‭Sorts the list in ascending order.‬


‭nums = [3, 1, 4, 2]‬
‭nums.sort()‬
‭print(nums) # [1, 2, 3, 4]‬

‭To sort in descending order:‬


‭nums.sort(reverse=True)‬

reverse()‬
‭10.‬‭

‭Reverses the order of elements.‬


‭nums = [1, 2, 3]‬
‭nums.reverse()‬
‭print(nums) # [3, 2, 1]‬

copy()‬
‭11.‬‭

‭Returns a shallow copy of the list.‬


‭a = [1, 2, 3]‬
‭b = a.copy()‬
‭print(b) # [1, 2, 3]‬

len(list)‬
‭12.‬‭

‭Returns the number of elements.‬


‭a = [10, 20, 30]‬
‭print(len(a)) # 3‬

‭Defining Strings‬
‭ ‬‭string‬‭is a sequence of characters enclosed in single or double‬
A
‭quotes.‬
‭ Using single quotes‬
#
‭string1 = 'Hello'‬

‭ Using double quotes‬


#
‭string2 = "World"‬

‭Basic String Operations‬

‭1.‬‭Accessing Characters (Indexing)‬‭: You can access individual‬


‭characters in a string using an index (starting from 0).‬

‭ y_string = "Python"‬
m
‭print(my_string[0]) # Output: 'P' (first character)‬
‭print(my_string[3]) # Output: 'h' (fourth character)‬

‭2.‬‭Slicing‬‭: You can extract a substring using slicing.‬

‭my_string = "Python"‬
‭ rint(my_string[1:4]) # Output: 'yth' (from index 1 to index 3)‬
p
‭print(my_string[:3]) # Output: 'Pyt' (from the start to index 2)‬
‭print(my_string[3:]) # Output: 'hon' (from index 3 to the end)‬

‭String Concatenation and Repetition‬

+‬
‭1.‬‭Concatenation‬‭: You can combine two strings using the‬‭
‭operator.‬

‭ reeting = "Hello"‬
g
‭name = "John"‬
‭message = greeting + " " + name‬
‭print(message) # Output: 'Hello John'‬

*‬‭operator.‬
‭2.‬‭Repetition‬‭: You can repeat a string using the‬‭

‭ ord = "Python"‬
w
‭print(word * 3) # Output: 'PythonPythonPython' (repeated 3 times)‬

‭String Length‬

len()‬‭function.‬
‭You can find the length of a string using the‬‭

‭ y_string = "Python"‬
m
‭print(len(my_string)) # Output: 6‬

‭String Methods‬

upper()‬‭and‬‭
‭1.‬‭ lower()‬
‭: Change the case of the string.‬
‭ y_string = "hello"‬
m
‭print(my_string.upper()) # Output: 'HELLO'‬
‭print(my_string.lower()) # Output: 'hello'‬

strip()‬
‭2.‬‭ ‭: Remove leading and trailing whitespace.‬

‭ y_string = " hello "‬


m
‭print(my_string.strip()) # Output: 'hello'‬

replace()‬
‭3.‬‭ ‭: Replace a substring with another substring.‬

‭ y_string = "hello world"‬


m
‭print(my_string.replace("world", "Python")) # Output: 'hello Python'‬

split()‬
‭4.‬‭ ‭: Split a string into a list based on a delimiter.‬

‭ y_string = "hello world python"‬


m
‭print(my_string.split()) # Output: ['hello', 'world', 'python']‬

find()‬
‭5.‬‭ ‭: Find the position of a substring in a string.‬

‭ y_string = "hello python"‬


m
‭print(my_string.find("python")) # Output: 6 (index of 'python')‬

‭SOME COMMON FUNCTIONS OF STRING‬

startswith()‬
‭1.‬‭

‭Checks if the string starts with the given value.‬


‭text = "welcome"‬
‭print(text.startswith("wel")) # True‬

endswith()‬
‭2.‬‭

‭Checks if the string ends with the given value.‬


f‭ile = "document.pdf"‬
‭print(file.endswith(".pdf")) # True‬

count()‬
‭3.‬‭

‭Returns the number of times a value appears.‬


‭ ord = "banana"‬
w
‭print(word.count("a")) # 3‬

capitalize()‬
‭4.‬‭

‭Capitalizes the first character of the string.‬


‭ sg = "python"‬
m
‭print(msg.capitalize()) # Python‬

title()‬
‭5.‬‭

‭Capitalizes the first letter of each word.‬


‭ entence = "hello world"‬
s
‭print(sentence.title()) # Hello World‬
swapcase()‬
‭6.‬‭

‭Swaps uppercase to lowercase and vice versa.‬


t‭ext = "HeLLo"‬
‭print(text.swapcase()) # hEllO‬

isdigit()‬
‭7.‬‭

‭Checks if all characters in the string are digits.‬


‭ um = "12345"‬
n
‭print(num.isdigit()) # True‬

isalpha()‬
‭8.‬‭

‭Checks if all characters are alphabets.‬


‭ ame = "Python"‬
n
‭print(name.isalpha()) # True‬

isalnum()‬
‭9.‬‭

‭Checks if all characters are alphanumeric (letters or digits).‬


‭ ser = "user123"‬
u
‭print(user.isalnum()) # True‬

isupper()‬
‭10.‬‭

‭Checks if all characters are uppercase.‬


‭x = "HELLO"‬
‭print(x.isupper()) # True‬

islower()‬
‭11.‬‭

‭Checks if all characters are lowercase.‬


‭ = "hello"‬
y
‭print(y.islower()) # True‬

‭Use Of Loops With Lists‬


for‬‭loop to access list elements‬
‭1. Using‬‭
‭fruits = ["apple", "banana", "cherry"]‬

‭for fruit in fruits:‬


‭print(fruit)‬

‭Full Explanation:‬

fruits‬‭is created with three string elements.‬


‭●‬ ‭A list named‬‭

for‬‭loop goes through each element of the list‬‭one by one.‬


‭●‬ ‭The‬‭

fruit‬‭becomes‬‭
‭●‬ ‭In the first iteration,‬‭ "apple"‬‭and‬‭gets printed.‬

fruit‬‭becomes‬‭
‭●‬ I‭n the second iteration,‬‭ "banana"‬‭and‬‭is‬
‭printed.‬

fruit‬‭becomes‬‭
‭●‬ ‭In the third iteration,‬‭ "cherry"‬‭and‬‭is printed.‬

‭●‬ ‭After that, the loop ends because all elements are covered.‬
‭Output:‬
‭ pple‬
a
‭banana‬
‭cherry‬

for‬‭loop with‬‭
‭2. Using‬‭ range()‬‭and index‬
‭numbers = [10, 20, 30, 40]‬

‭for i in range(len(numbers)):‬
‭print("Index", i, "has value", numbers[i])‬

‭Full Explanation:‬

numbers‬‭contains four integers.‬


‭●‬ ‭A list‬‭

‭●‬ ‭
len(numbers)‬‭returns 4, so‬‭
range(4)‬‭gives:‬‭
0, 1, 2, 3‬
‭.‬

i‬‭as index:‬
‭●‬ ‭The loop runs 4 times, each time with‬‭

i = 0‬
‭○‬ ‭When‬‭ Index 0 has value 10‬
‭: it prints‬‭

i = 1‬
‭○‬ ‭When‬‭ Index 1 has value 20‬
‭: it prints‬‭

i = 2‬
‭○‬ ‭When‬‭ Index 2 has value 30‬
‭: it prints‬‭

i = 3‬
‭○‬ ‭When‬‭ Index 3 has value 40‬
‭: it prints‬‭

numbers[0]‬
‭●‬ I‭t accesses elements by index like‬‭ numbers[1]‬
‭,‬‭ ‭,‬
‭etc.‬

‭Output:‬
I‭ndex 0 has value 10‬
‭Index 1 has value 20‬
‭Index 2 has value 30‬
‭Index 3 has value 40‬

while‬‭loop to access list elements‬


‭3. Using‬‭
‭ olors = ["red", "green", "blue"]‬
c
‭i = 0‬

‭while i < len(colors):‬


‭print(colors[i])‬
‭i += 1‬

‭Full Explanation:‬

colors‬‭has 3 strings.‬
‭●‬ ‭The list‬‭

i‬‭is initialized to‬‭


‭●‬ ‭The variable‬‭ 0‬‭.‬

‭●‬ w
‭hile i < len(colors)‬‭checks whether‬‭
i‬‭is less than‬‭the‬
‭length (3).‬

‭●‬ ‭In each loop:‬

i‭,‬like‬‭
‭○‬ I‭t prints the value at index‬‭ colors[0]‬ colors[1]‬
‭,‬‭ ‭,‬
‭etc.‬

i‬‭is increased by 1.‬


‭○‬ ‭Then‬‭
i‬‭becomes 3, the loop stops.‬
‭●‬ ‭When‬‭

‭Step by step:‬

‭●‬ ‭
i = 0‬‭→ prints‬‭
"red"‬‭→‬‭
i = 1‬

‭●‬ ‭
i = 1‬‭→ prints‬‭
"green"‬‭→‬‭
i = 2‬

‭●‬ ‭
i = 2‬‭→ prints‬‭
"blue"‬‭→‬‭
i = 3‬

‭●‬ ‭
i = 3‬‭→ loop stops‬

‭Output:‬
r‭ ed‬
‭green‬
‭blue‬

‭Sorting in Python‬
‭What is Sorting?‬

‭ orting‬‭is the process of arranging elements in a‬‭specific‬


S
‭order‬‭—usually in‬‭ascending‬‭(small to large) or‬‭descending‬‭(large to‬
‭small) order.‬
‭In Python, sorting is often used for:‬

[3, 5, 2, 1] → [1, 2, 3, 5]‬


‭●‬ ‭Numbers (e.g.,‬‭ ‭)‬

‭●‬ S ["apple", "banana", "cherry"] →‬


‭ trings (e.g.,‬‭
alphabetic order‬
‭ ‭)‬
‭●‬ ‭Organizing data to make it easier to read or search.‬

‭How Sorting Works in Python‬

‭Python provides two main ways to sort lists:‬


.sort()‬‭method‬
‭1.‬‭

‭●‬ ‭Used‬‭on the list directly‬

‭●‬ ‭Modifies the original list‬

‭Syntax:‬

‭list_name.sort()‬
‭●‬
sorted()‬‭function‬
‭2.‬‭

‭●‬ ‭Used to create a‬‭new sorted list‬

‭●‬ ‭Does‬‭not change the original‬

‭Syntax:‬

‭sorted_list = sorted(original_list)‬
‭●‬

‭Sorting in Ascending Order (Default)‬


‭ umbers = [5, 3, 9, 1, 4]‬
n
‭numbers.sort()‬
‭print(numbers)‬
‭Explanation:‬

‭●‬ T .sort()‬‭method arranges the list from‬‭smallest‬‭to‬


‭ he‬‭
‭largest‬‭.‬

‭Output will be:‬

‭[1, 3, 4, 5, 9]‬

‭Sorting in Descending Order‬


‭ alues = [10, 7, 2, 5, 8]‬
v
‭values.sort(reverse=True)‬
‭print(values)‬

‭Explanation:‬

reverse=True‬‭sorts from‬‭largest to smallest‬‭.‬


‭●‬ ‭Using‬‭

‭Output will be:‬

‭[10, 8, 7, 5, 2]‬
‭●‬

sorted()‬‭(non-destructive)‬
‭Using‬‭
‭ cores = [55, 90, 66, 33]‬
s
‭sorted_scores = sorted(scores)‬
‭print("Original:", scores)‬
‭print("Sorted:", sorted_scores)‬
‭Explanation:‬

‭●‬ ‭
sorted()‬‭gives a‬‭new list‬‭.‬

scores‬‭remains unchanged.‬
‭●‬ ‭The original‬‭

‭Output:‬

‭ riginal: [55, 90, 66, 33]‬


O
‭Sorted: [33, 55, 66, 90]‬

‭LIST OF PYTHON FUNCTIONS & OPERATIONS‬


‭1. Copying a List‬

.copy()‬‭method.‬
‭ ou can create an exact copy of a list using the‬‭
Y
‭This is useful when you want to preserve the original list and work on‬
‭a duplicate.‬
‭ riginal = [1, 2, 3]‬
o
‭copy_list = original.copy()‬
‭print(copy_list)‬

‭Output:‬
[1, 2, 3]‬

copy_list‬‭is now a separate copy of‬‭
‭The list‬‭ original‬ ‭,‬‭meaning‬
‭any changes made to‬‭ copy_list‬‭won’t affect the original‬‭list.‬

‭2. Copying a List Using Slicing‬

‭ nother way to copy a list is by using slicing (‬‭


A [:]‬
‭),‬‭which creates a‬
‭shallow copy.‬
‭ = [10, 20, 30]‬
a
‭b = a[:]‬
‭print(b)‬

‭Output:‬
[10, 20, 30]‬

b‬‭is a new list that contains the‬‭same values as‬‭
‭Here, the list‬‭ a‭.‬‬

‭3. Slicing a List‬

‭ licing is used to extract a portion of a list. It uses the syntax‬


S
[start:stop]‬
‭ ‭, where the start index is included and‬‭the stop index‬
‭is excluded.‬
‭ ums = [10, 20, 30, 40, 50]‬
n
‭print(nums[1:4])‬

‭Output:‬
[20, 30, 40]‬

‭This returns a new list with elements from index 1 to index 3 (4 is‬
‭excluded).‬

‭4. Inserting an Element‬

‭ ou can insert an element into a specific position in a list using the‬


Y
.insert(index, value)‬‭method.‬

f‭ruits = ['apple', 'banana']‬


‭fruits.insert(1, 'mango')‬
‭print(fruits)‬

‭Output:‬
['apple', 'mango', 'banana']‬

'mango'‬‭is inserted at index 1, shifting the other elements to‬
‭ ere,‬‭
H
‭the right.‬

‭5. Extending a List‬

.extend()‬‭method adds all elements from another‬‭list to the‬


‭ he‬‭
T
‭end of the current list.‬
‭ = [1, 2]‬
x
‭y = [3, 4]‬
‭x.extend(y)‬
‭print(x)‬

‭Output:‬
[1, 2, 3, 4]‬

y‬‭are added to the end of list‬‭
‭All elements of list‬‭ x‭.‬‬

‭6. Removing an Element by Value‬

‭ ou can remove the first occurrence of a specific value from a list‬


Y
.remove(value)‬
‭using‬‭ ‭.‬

‭ ames = ['Ali', 'Sara', 'Ali']‬


n
‭names.remove('Ali')‬
‭print(names)‬

‭Output:‬
['Sara', 'Ali']‬

'Ali'‬‭is removed. The second one remains.‬
‭Only the first‬‭

‭7. Removing an Element by Index‬


.pop(index)‬
‭ o remove an element at a specific position, use the‬‭
T
‭method.‬
‭ arks = [70, 80, 90]‬
m
‭marks.pop(1)‬
‭print(marks)‬

‭Output:‬
[70, 90]‬

‭The value at index 1 (which is 80) is removed from the list.‬

del‬
‭8. Deleting an Element using‬‭

‭ he‬‭
T del‬‭keyword is used to delete an element at a given index‬
‭directly.‬
‭ ata = [5, 10, 15]‬
d
‭del data[2]‬
‭print(data)‬

‭Output:‬
[5, 10]‬

‭The element at index 2 is deleted from the list.‬

‭9. Finding the Index of an Element‬

‭ o get the index of the first occurrence of a value in a list, use‬


T
.index(value)‬
‭ ‭.‬

‭ olors = ['red', 'blue', 'green']‬


c
‭print(colors.index('blue'))‬
‭Output:‬
1‬

'blue'‬‭is found at index 1 in the list.‬
‭The string‬‭

‭10. Counting Occurrences‬

.count(value)‬‭method to count how many times‬‭a value‬


‭ se the‬‭
U
‭appears in the list.‬
‭ ums = [1, 2, 2, 3, 2]‬
n
‭print(nums.count(2))‬

‭Output:‬
3‬

2‬‭appears three times in the list.‬
‭The number‬‭

‭11. Reversing a List‬

.reverse()‬
‭ o reverse the order of elements in a list, use the‬‭
T
‭method.‬
i‭tems = [1, 2, 3]‬
‭items.reverse()‬
‭print(items)‬

‭Output:‬
[3, 2, 1]‬

‭The list is reversed in-place, changing the original list.‬

‭Tuples in Python‬
‭Definition:‬

‭ ‬‭tuple‬‭is a‬‭collection of ordered and immutable elements‬‭in‬


A
‭Python.‬
‭Unlike lists, once a tuple is created,‬‭its elements cannot be‬
‭changed (immutable)‬‭. Tuples are defined using‬‭parentheses‬‭ ( )‬
‭.‬

I‭t is basically same as lists with some differences.Moreover Most‬


‭part remains same.‬

‭Creating a Tuple‬
‭ y_tuple = (10, 20, 30)‬
m
‭print(my_tuple)‬

‭Output:‬
(10, 20, 30)‬

‭Tuple with Different Data Types‬


‭ ixed = ("apple", 25, True)‬
m
‭print(mixed)‬

‭Output:‬
('apple', 25, True)‬

‭Note:‬
‭●‬ T
‭ uples can contain‬‭any type of data‬‭(strings, numbers,‬
‭booleans, etc.).‬

‭●‬ ‭They are‬‭faster‬‭and use‬‭less memory‬‭than lists.‬

‭●‬ I‭mmutable‬‭means you‬‭cannot add, remove, or change‬


‭elements‬‭once created.‬

‭Difference Between List and Tuple‬

‭Feature‬ ‭List‬ ‭Tuple‬


‭Definition‬ ‭ rdered and mutable‬
O ‭ rdered and immutable‬
O
‭collection‬ ‭collection‬
‭Syntax‬ ‭ efined using square‬
D ‭ efined using‬
D
[ ]‬
‭brackets‬‭ ( )‬
‭parentheses‬‭
‭Mutability‬ ‭ utable – can be‬
M I‭mmutable – cannot be‬
‭changed‬ ‭changed‬
‭Speed‬ ‭Slower than tuple‬ ‭Faster than list‬
‭ emory‬
M ‭Uses more memory‬ ‭Uses less memory‬
‭Usage‬
‭ unctions‬
F ‭ ore methods (e.g.,‬
M ‭ ewer methods‬
F
‭Available‬ append‬
‭ remove‬
‭,‬‭ ‭)‬ ‭available‬
‭Usage‬ ‭ sed when data may‬
U ‭ sed when data is‬
U
‭change‬ ‭fixed/constant‬

‭Example of List:‬
‭ y_list = [1, 2, 3]‬
m
‭my_list.append(4)‬
‭print(my_list)‬

‭Output:‬
[1, 2, 3, 4]‬‭(You can modify it)‬

‭Example of Tuple:‬
‭ y_tuple = (1, 2, 3)‬
m
‭# my_tuple.append(4) → This will give an error‬
‭print(my_tuple)‬

‭Output:‬
(1, 2, 3)‬‭(You cannot add or change elements)‬

‭When to Use a List:‬


‭●‬ ‭When you‬‭need to change, update, or delete‬‭elements.‬

‭●‬ W
‭ hen you are‬‭storing dynamic data‬‭(like user input‬‭or items‬
‭that grow/shrink).‬
‭●‬ W append()‬
‭ hen you plan to‬‭use built-in methods‬‭like‬‭ ‭,‬
remove()‬
‭ sort()‬
‭, or‬‭ ‭.‬

‭ xample Use Case:‬


E
‭A shopping cart where items may be added or removed.‬
‭ art = ["apple", "banana"]‬
c
‭cart.append("orange") # Changing data‬

‭When to Use a Tuple:‬


‭●‬ ‭When you want to store‬‭constant or fixed data‬‭.‬

‭●‬ W
‭ hen you want to ensure‬‭data doesn't get modified‬
‭accidentally‬‭.‬

‭●‬ W
‭ hen you're using the data as‬‭keys in a dictionary‬‭(only‬
‭immutable types can be keys).‬

‭●‬ ‭When you need‬‭better performance‬‭(faster and less‬‭memory).‬

‭ xample Use Case:‬


E
‭Storing days of the week, geographic coordinates, or configurations.‬
‭ ays = ("Mon", "Tue", "Wed", "Thu", "Fri")‬
d
‭location = (27.7, 85.3) # (latitude, longitude)‬

‭Simple Rule:‬

‭ se lists when data can change, tuples when it‬


U
‭shouldn't.‬
‭1. Accessing Elements Using Index‬
‭ uples are ordered, so you can access elements by index (starting‬
T
‭from 0).‬
t‭ = (10, 20, 30, 40)‬
‭print(t[1]) # Access second element‬

‭Output:‬
20‬

‭2. Tuple Slicing‬


‭You can extract a part of the tuple using slicing.‬
t‭ = (1, 2, 3, 4, 5)‬
‭print(t[1:4]) # From index 1 to 3‬

‭Output:‬
(2, 3, 4)‬

‭3. Looping Through a Tuple‬


‭You can use a loop to go through each item.‬
‭ olors = ("red", "green", "blue")‬
c
‭for color in colors:‬
‭print(color)‬

‭Output:‬
r‭ ed‬
‭green‬
‭blue‬

‭4. Tuple Methods‬


count(value)‬‭– counts how many times a value occurs:‬

t‭ = (1, 2, 2, 3)‬
‭print(t.count(2))‬

‭Output:‬
2‬

index(value)‬‭– returns the index of the first match:‬

t‭ = (5, 10, 15, 10)‬


‭print(t.index(10))‬

‭Output:‬
1‬

‭5. Nested Tuples‬


‭A tuple can contain other tuples.‬
t‭ = (1, (2, 3), (4, 5))‬
‭print(t[1][0]) # Accessing 2 from nested tuple‬

‭Output:‬
2‬

‭6. Tuple Unpacking‬
‭You can assign values from a tuple to variables directly.‬
‭ erson = ("John", 25)‬
p
‭name, age = person‬
‭print(name)‬
‭print(age)‬

‭Output:‬
‭ ohn‬
J
‭25‬

‭7. Tuples as Dictionary Keys‬


‭Only immutable types like tuples can be used as dictionary keys.‬
l‭ocation = {(27.7, 85.3): "Kathmandu"}‬
‭print(location[(27.7, 85.3)])‬

‭Output:‬
Kathmandu‬

‭8. Converting Between List and Tuple‬


‭List to Tuple:‬
l‭st = [1, 2, 3]‬
‭t = tuple(lst)‬
‭print(t)‬
‭Output:‬
(1, 2, 3)‬

‭Tuple to List:‬
t‭up = (4, 5, 6)‬
‭lst = list(tup)‬
‭print(lst)‬

‭Output:‬
[4, 5, 6]‬

‭PROGRAMS‬

‭1. Write a program to create a list of fruits and print each fruit using a loop.‬
f‭ruits = ["apple", "banana", "mango"]‬
‭for fruit in fruits:‬
‭print(fruit)‬

‭ . Write a program to access and display the third element from a list of‬
2
‭integers.‬
‭ umbers = [10, 20, 30, 40, 50]‬
n
‭print(numbers[2]) # Output: 30‬

‭ . Write a program to accept 5 elements from the user, store them in a list,‬
3
‭and display the list.‬
‭elements = []‬
‭for i in range(5):‬
‭item = input("Enter an element: ")‬
‭elements.append(item)‬
‭print(elements)‬

‭4. Write a program to insert a user-given value at a specific index in a list.‬


‭ arks = [80, 85, 90]‬
m
‭value = int(input("Enter the value to insert: "))‬
‭index = int(input("Enter the index: "))‬
‭marks.insert(index, value)‬
‭print(marks)‬

‭5. Write a program to remove a given item from the list.‬


‭ olors = ["red", "blue", "green"]‬
c
‭item = input("Enter color to remove: ")‬
‭colors.remove(item)‬
‭print(colors)‬

‭6. Write a program to sort a list of integers in ascending order.‬


‭ ums = [3, 1, 4, 2]‬
n
‭nums.sort()‬
‭print(nums)‬

‭7. Write a program to reverse the elements of a list.‬


l‭etters = ['a', 'b', 'c']‬
‭letters.reverse()‬
‭print(letters)‬
‭ . Write a program to copy the contents of one list into another and display‬
8
‭both.‬
‭ riginal = [1, 2, 3]‬
o
‭copied = original.copy()‬
‭print("Original list:", original)‬
‭print("Copied list:", copied)‬

‭ . Write a program to slice a list and display selected elements from index 1‬
9
‭to 3.‬
‭ ata = [10, 20, 30, 40, 50]‬
d
‭print(data[1:4])‬

‭ 0. Write a program to count how many times a number appears in a list‬


1
‭and find its index.‬
‭ ums = [5, 3, 5, 2]‬
n
‭print("Count of 5:", nums.count(5))‬
‭print("Index of 2:", nums.index(2))‬

‭ 1. Write a program to take a list of numbers from the user and display only‬
1
‭the even numbers.‬
‭ ums = []‬
n
‭for i in range(5):‬
‭val = int(input("Enter a number: "))‬
‭nums.append(val)‬
‭for num in nums:‬
‭if num % 2 == 0:‬
‭print(num)‬

‭12. Write a program to find the sum of all elements in a list.‬


‭numbers = [10, 20, 30, 40]‬
t‭otal = 0‬
‭for num in numbers:‬
‭total += num‬
‭print("Sum =", total)‬

‭13. Write a program to multiply all elements in a list.‬


‭ umbers = [2, 3, 4]‬
n
‭product = 1‬
‭for num in numbers:‬
‭product *= num‬
‭print("Product =", product)‬

‭14. Write a program to find the largest and smallest element in a list.‬
‭ umbers = [12, 4, 67, 34, 89]‬
n
‭print("Max:", max(numbers))‬
‭print("Min:", min(numbers))‬

‭15. Write a program to count the number of even and odd numbers in a list.‬
‭ umbers = [1, 2, 3, 4, 5, 6]‬
n
‭even = odd = 0‬
‭for num in numbers:‬
‭if num % 2 == 0:‬
‭even += 1‬
‭else:‬
‭odd += 1‬
‭print("Even:", even)‬
‭print("Odd:", odd)‬

‭ 6. Write a program to accept 5 strings from the user, store in a list and‬
1
‭display only those starting with a vowel.‬
‭ ords = []‬
w
‭for i in range(5):‬
‭word = input("Enter a word: ")‬
‭words.append(word)‬
‭for word in words:‬
‭if word[0].lower() in "aeiou":‬
‭print(word)‬

‭17. Write a program to concatenate two lists and print the final list.‬
l‭ist1 = [1, 2, 3]‬
‭list2 = [4, 5, 6]‬
‭final = list1 + list2‬
‭print(final)‬

‭18. Write a program to clear all elements from a list.‬


i‭tems = [10, 20, 30]‬
‭items.clear()‬
‭print("List after clearing:", items)‬

‭19. Write a program to copy only unique values from one list to another.‬
‭ riginal = [1, 2, 2, 3, 4, 4, 5]‬
o
‭unique = []‬
‭for i in original:‬
‭if i not in unique:‬
‭unique.append(i)‬
‭print("Unique values:", unique)‬

‭20. Write a program to create a nested list and access elements from it.‬
‭nested = [[1, 2], [3, 4], [5, 6]]‬
‭print(nested[1][0]) # Output: 3‬

‭21. Write a program to find the second largest number in a list.‬


‭ umbers = [12, 45, 32, 67, 89, 45]‬
n
‭numbers.sort()‬
‭print("Second largest number:", numbers[-2])‬

‭22. Write a program to remove all duplicate elements from a list.‬


‭ umbers = [1, 2, 2, 3, 4, 4, 5]‬
n
‭unique = list(set(numbers))‬
‭print("List without duplicates:", unique)‬

‭23. Write a program to split a sentence into words and store them in a list.‬
‭ entence = input("Enter a sentence: ")‬
s
‭words = sentence.split()‬
‭print("Words:", words)‬

‭24. Write a program to convert all elements of a list from strings to integers.‬
‭ tr_list = ["1", "2", "3"]‬
s
‭int_list = [int(i) for i in str_list]‬
‭print("Converted list:", int_list)‬

‭25. Write a program to find common elements in two lists.‬


l‭ist1 = [1, 2, 3, 4]‬
‭list2 = [3, 4, 5, 6]‬
‭common = [i for i in list1 if i in list2]‬
‭print("Common elements:", common)‬

‭ 6. Write a program to print the index of all occurrences of a number in a‬


2
‭list.‬
‭ ums = [5, 3, 5, 2, 5]‬
n
‭for i in range(len(nums)):‬
‭if nums[i] == 5:‬
‭print("5 found at index:", i)‬

‭27. Write a program to print all elements at even indexes in a list.‬


i‭tems = [10, 20, 30, 40, 50, 60]‬
‭for i in range(0, len(items), 2):‬
‭print(items[i])‬

‭28. Write a program to convert a list of characters into a string.‬


‭ hars = ['P', 'y', 't', 'h', 'o', 'n']‬
c
‭result = ''.join(chars)‬
‭print("String:", result)‬

‭29. Write a program to find the frequency of each element in a list.‬


‭ ums = [1, 2, 2, 3, 3, 3]‬
n
‭freq = {}‬
‭for num in nums:‬
‭if num in freq:‬
‭freq[num] += 1‬
‭else:‬
‭freq[num] = 1‬
‭print("Frequencies:", freq)‬
‭30. Write a program to check whether a list is a palindrome.‬
l‭st = [1, 2, 3, 2, 1]‬
‭if lst == lst[::-1]:‬
‭print("Palindrome list")‬
‭else:‬
‭print("Not a palindrome")‬

len()‬‭function.‬
‭31. Write a program to find the length of a string using‬‭
t‭ext = "Hello World"‬
‭print("Length of the string:", len(text))‬
‭# Output: Length of the string: 11‬

‭32. Write a program to convert a string to lowercase and uppercase.‬


‭ = "Python Programming"‬
s
‭print("Lowercase:", s.lower())‬
‭print("Uppercase:", s.upper())‬
‭# Output:‬
‭# Lowercase: python programming‬
‭# Uppercase: PYTHON PROGRAMMING‬

strip()‬
‭33. Write a program to remove leading and trailing spaces using‬‭ ‭.‬
‭ sg = " Hello Python "‬
m
‭print("After strip:", msg.strip())‬
‭# Output: After strip: Hello Python‬

‭ 4. Write a program to remove spaces only from the left and right using‬
3
lstrip()‬‭and‬‭
‭ rstrip()‬ ‭.‬
‭ ata = " Welcome! "‬
d
‭print("Left strip:", data.lstrip())‬
‭ rint("Right strip:", data.rstrip())‬
p
‭# Output:‬
‭# Left strip: Welcome!‬
‭# Right strip: Welcome!‬

find()‬
‭35. Write a program to find the position of a word using‬‭ ‭.‬
t‭ext = "Python is awesome"‬
‭print("Position of 'is':", text.find("is"))‬
‭# Output: Position of 'is': 7‬

replace()‬
‭36. Write a program to replace a word in a string using‬‭ ‭.‬
‭ sg = "I love apples"‬
m
‭print("After replace:", msg.replace("apples", "oranges"))‬
‭# Output: After replace: I love oranges‬
‭ 7. Write a program to count how many times a word appears using‬
3
count()‬
‭ ‭.‬
‭ entence = "apple banana apple mango apple"‬
s
‭print("Count of 'apple':", sentence.count("apple"))‬
‭# Output: Count of 'apple': 3‬

split()‬‭function.‬
‭38. Write a program to split a sentence into words using‬‭
l‭ine = "Python is easy to learn"‬
‭print("Words:", line.split())‬
‭# Output: Words: ['Python', 'is', 'easy', 'to', 'learn']‬

join()‬‭function.‬
‭39. Write a program to join a list of words using‬‭
‭ ords = ['Python', 'is', 'fun']‬
w
‭print("Sentence:", " ".join(words))‬

You might also like