Python (Preview Only)
Python (Preview Only)
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.
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
In 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.
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.
● A
variable name must start with a letter or an underscore,nota
number.
print()Function
The
print("Hello, World!")
Output:
Hello, World!
Programs:
.Declare a variable to store your name and printit.
1
name = "Alice"
print(name)
Output:
Alice
ageand
2.Declare two variables, height
, and print them
together.
ge = 25
a
height = 5.6
print(age, height)
Output:
25 5.6
is_student = True
print(is_student)
Output:
True
#.
4.Print "Python", "is", "awesome" separated by
print("Python", "is", "awesome", sep="#")
Output:
Python#is#awesome
Helloand
5.Print two statements Worldon the same line.
Output:
ood
G
Morning
ity = "Paris"
c
country = "France"
print("City:", city, ", Country:", country)
Output:
City: Paris , Country: France
8.Question:
Print the following using a newline (
\n) betweenwords:
Welcome
to
Python
Answer:
print("Welcome\to\nPython")
Output:
elcome
W
to
Python
10.Question:
aand
wap the values of two variables
S bwithoutusing 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 = 100and
y = 50are
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 nameand 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:
length = 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:
integer = 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 astring.
Example:
Taking input from the user
#
name = input("Enter your name: ")
Output:
nter your name: Alice
E
Alice
Usage:
input()
● Toaccept user input, you use .
● T
he function always returns the input as astring,even if the
user types in numbers. You can convert it to other data types if
intor
needed (like float
).
Alice
Output:
nter your age: 25
E
Your age is: 25
Output:
nter your height: 5.8
E
Your height is: 5.8
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
print(num_float)
Output:
7.0
rint(num_int)
p
Output:
8
4. Boolean to Integer
flag = True
num = int(flag)
print(num)
Output:
1
print(text)
Output:
25
rint(a)
p
print(b)
Example Input:
Enter two numbers: 10 20
Output:
0
1
20
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)
3.Q. Take a float input from the user and print it.
eight = float(input("Enter your height: "))
h
print(height)
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)
Basic Logic:
In Python,
if
else
, elifare used tomake decisionsbasedon certain
, and
conditions.
●
ifchecks a condition. If it isTrue, the code inside it runs.
●
elseruns when the
ifcondition isFalse.
●
elif(else if) checksanother conditionif the first
ifis 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
How elif
, elseworks:
,
ifblock:
1.
ifcondition first.
○ Python checks the
elseblock:
3.
ifand
○ Ifnone of the elifconditions are True, then
elseruns.
○ Itdoes not check any condition, it runs directly when all
previous checks fail.
Full Working Example + True Case Flow
marks = int(input("Enter your marks: "))
Example Walkthrough
Input What Happens?
Marks
(say)
95 fcondition
i marks >= 90is True → prints "Grade:
A" → stops checking further
78 fis False → checks first
i elif→
marks >= 75is
True → prints "Grade: B"
62 fFalse → first
i elifFalse → second
elif
marks
>= 60True → prints "Grade: C"
45 elif
ll previous False → third
A marks >= 40True
→ prints "Grade: D"
30 ifand
ll
A elifFalse → runs
else→ prints "Grade:
F"
Explanation:
●
andoperator:
○ T
he conditionage >= 18 and citizenship.lower()
== "yes"meansboth conditions must be Truefor the
block to run.
○ F
or example, a person aged 20 who is a citizen will enter
this block.
●
elifwith
and
:
○ T
he second elifchecks ifage is >= 18butcitizenshipis
not "yes"(i.e., they are not a citizen). The blockwill
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: "))
Explanation:
if
● First : It checks if the person is18 or older.
● N
estedif if
: Inside the first , another check is doneto see if
themonthly income is greater than or equal to 5000.
○ If both conditions are met, the person is eligible for the
loan.
○ If 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.
Explanation:
"Even"
○ IfTrue, it returns .
"Odd"
○ IfFalse, it returns .
● T
his is a concise way of doing a check that would otherwise
require anif-elseblock.
PROGRAMS
if-elif-else
14. Check if a number is positive, negative, or zero using :
number = int(input("Enter a number: "))
—------------------------------------------------------------------------------------------
Chapter 4 — Loops
Definition:
loopis 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.
Example:
i = 1
while i <= 5:
print(i)
i = i + 1
Detailed Execution:
Final Output:
1
2
3
4
5
● 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
Final Output:
1
2
3
4
5
Break Statement
Meaning:
● T breakstatement is used toimmediately stoptheloop,
he
even if the condition is still true.
Example:
i = 1
while i <= 5:
if i == 3:
break
print(i)
i = i + 1
Detailed Execution:
Final Output:
1
2
Continue Statement
Meaning:
● T
hecontinuestatement is used toskip the currentiteration
andjump to the nextiteration of the loop.
● It 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
3is skipped because of
(Note: continue
.)
Indentation in Python
Meaning:
● Indentationmeansadding spacesortabsat the beginning of a
line.
Important Points:
● Indentation is usually4 spaces.
● A
ll the statements inside a block (like loop, if-else) must be
indented equally.
● W
ithout proper indentation,Python doesn't know whichlines
are part of the block.
Example:
i = 1
while i <= 3:
print(i)
i = i + 1
Detailed Execution:
Final Output:
1
2
3
● P print(i)
ython will show anIndentationErrorbecause the
line isnot indentedproperly.
● T
heinner loopruns completely for everysingle repetitionof
theouter loop.
● U
seful when we work withpatterns,tables,multi-level data,
etc.
Working Logic:
uter loop starts ➔ inner loop runsfully➔ then outerloop
● 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:
● i = 2:
● i = 3:
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
i = 1
while i <= 2:
j = 1
while j <= 3:
print(i, j)
j = j + 1
i = i + 1
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
i = 1
while i <= 4:
j = 1
while j <= i:
print(j, end=' ')
j = j + 1
print()
i = i + 1
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 = 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
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
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
i = 1
while i <= 4:
j = 1
while j <= i:
print(i, end=' ')
j = j + 1
print()
i = i + 1
i = 4
while i >= 1:
j = 1
while j <= i:
print(i, end=' ')
j = j + 1
print()
i = i - 1
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
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
i = 1
while i <= 4:
j = 1
while j <= i:
print(chr(64 + j), end=' ')
j = j + 1
print()
i = i + 1
i = 4
while i >= 1:
j = 1
while j <= i:
print(chr(64 + j), end=' ')
j = j + 1
print()
i = i - 1
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 = 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
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
i = 1
while i <= 4:
j = 1
while j <= i:
rint(chr(64 + i), end=' ')
p
j = j + 1
print()
i = i + 1
i = 1
while i <= 4:
j = 1
while j <= i:
print(chr(64 + i), end=' ')
j = j + 1
print()
i = i + 1
def sum_of_digits(num):
if num == 0:
return 0
else:
return num % 10 + sum_of_digits(num // 10)
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")
[]
In 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"]
Example:
fruits = ["apple", "banana", "cherry"]
Explanation of Indexing:
●
fruits[0] "apple"
: This refers to the first element, which is .
● f
ruits[1] : This refers to the second element, whichis
"banana"
.
● f
ruits[-1] : This refers to the last element, whichis
"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"]
3. Taking User Input to Store a Value in the List and Print the Updated List:
Initial list
#
fruits = ["apple", "banana", "cherry"]
append()
1.
insert(index, element)
2.
extend(iterable)
3.
remove(value)
4.
pop(index)
5.
clear()
6.
Removes all elements from the list.
nums = [1, 2, 3]
nums.clear()
print(nums) # []
index(value)
7.
count(value)
8.
sort()
9.
reverse()
10.
copy()
11.
len(list)
12.
Defining Strings
stringis a sequence of characters enclosed in single or double
A
quotes.
Using single quotes
#
string1 = 'Hello'
y_string = "Python"
m
print(my_string[0]) # Output: 'P' (first character)
print(my_string[3]) # Output: 'h' (fourth character)
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)
+
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.
replace()
3. : Replace a substring with another substring.
split()
4. : Split a string into a list based on a delimiter.
find()
5. : Find the position of a substring in a string.
startswith()
1.
endswith()
2.
count()
3.
capitalize()
4.
title()
5.
isdigit()
7.
isalpha()
8.
isalnum()
9.
isupper()
10.
islower()
11.
Full Explanation:
fruitbecomes
● In the first iteration, "apple"andgets printed.
fruitbecomes
● In the second iteration, "banana"andis
printed.
fruitbecomes
● In the third iteration, "cherry"andis printed.
● After that, the loop ends because all elements are covered.
Output:
pple
a
banana
cherry
forloop 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:
●
len(numbers)returns 4, so
range(4)gives:
0, 1, 2, 3
.
ias 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]
● It accesses elements by index like numbers[1]
, ,
etc.
Output:
Index 0 has value 10
Index 1 has value 20
Index 2 has value 30
Index 3 has value 40
Full Explanation:
colorshas 3 strings.
● The list
● w
hile i < len(colors)checks whether
iis less thanthe
length (3).
i,like
○ It prints the value at index colors[0] colors[1]
, ,
etc.
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?
Syntax:
list_name.sort()
●
sorted()function
2.
Syntax:
sorted_list = sorted(original_list)
●
[1, 3, 4, 5, 9]
Explanation:
[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 anew list.
scoresremains unchanged.
● The original
Output:
.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_listis now a separate copy of
The list original ,meaning
any changes made to copy_listwon’t affect the originallist.
Output:
[10, 20, 30]
bis a new list that contains thesame values as
Here, the list a.
Output:
[20, 30, 40]
This returns a new list with elements from index 1 to index 3 (4 is
excluded).
Output:
['apple', 'mango', 'banana']
'mango'is inserted at index 1, shifting the other elements to
ere,
H
the right.
Output:
[1, 2, 3, 4]
yare added to the end of list
All elements of list x.
Output:
['Sara', 'Ali']
'Ali'is removed. The second one remains.
Only the first
Output:
[70, 90]
The value at index 1 (which is 80) is removed from the list.
del
8. Deleting an Element using
he
T delkeyword 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.
Output:
3
2appears three times in the list.
The number
.reverse()
o reverse the order of elements in a list, use the
T
method.
items = [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:
Creating a Tuple
y_tuple = (10, 20, 30)
m
print(my_tuple)
Output:
(10, 20, 30)
Output:
('apple', 25, True)
Note:
● T
uples can containany type of data(strings, numbers,
booleans, etc.).
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)
● W
hen you arestoring dynamic data(like user inputor items
that grow/shrink).
● W append()
hen you plan touse built-in methodslike ,
remove()
sort()
, or .
● W
hen you want to ensuredata doesn't get modified
accidentally.
● W
hen you're using the data askeys in a dictionary(only
immutable types can be keys).
Simple Rule:
Output:
20
Output:
(2, 3, 4)
Output:
r ed
green
blue
Output:
2
index(value)– returns the index of the first match:
Output:
1
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
Output:
Kathmandu
Tuple to List:
tup = (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.
fruits = ["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)
. 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])
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)
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.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
final = list1 + list2
print(final)
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
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)
len()function.
31. Write a program to find the length of a string using
text = "Hello World"
print("Length of the string:", len(text))
# Output: Length of the string: 11
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 .
text = "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
line = "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))