Final Python Lab Manual
Final Python Lab Manual
# loop from 1 to 10
for i in range(1, 11):
x_sum = previous_num + i
print("Current Number", i, "Previous Number ", previous_num, "
Sum: ", x_sum)
previous_num = i
#Check if the first and last numbers of a list are the same
def first_last_same(numberList):
print("Given list:", numberList)
first_num = numberList[0]
last_num = numberList[-1]
if first_num == last_num:
return True
else:
return False
def palindrome(number):
print("original number", number)
original_num = number
# check numbers
if original_num == reverse_num:
print("Given number palindrome")
else:
print("Given number is not palindrome")
palindrome(121)
palindrome(125)
if num % 2 != 0:
result_list.append(num)
if num % 2 == 0:
result_list.append(num)
return result_list
exponent(5, 4)
My**Name**Is**James
10
num = 458.541315
print('%.2f' % num)
458.54
numbers = []
item = float(input())
numbers.append(item)
quantity = 3
totalMoney = 1000
price = 450
statement1 = "I have {1} dollars so I can buy {0} football for {2:.2f}
dollars."
print(statement1.format(quantity, totalMoney, price))
i = 1
while i <= 10:
print(i)
i += 1
1
2
3
4
5
6
7
8
9
10
s = 0
n = int(input("Enter number "))
s += i
print("\n")
print("Sum is: ", s)
Enter number 6
Sum is: 21
n = 2
product = n * i
print(product)
2
4
6
8
10
12
14
16
18
20
elif item % 5 == 0:
print(item)
75
150
145
num = 75869
count = 0
while num != 0:
num = num // 10
count = count + 1
print("Total digits are:", count)
new_list = reversed(list1)
50
40
30
20
10
-10
-9
-8
-7
-6
-5
-4
-3
-2
-1
for i in range(5):
print(i)
else:
print("Done!")
0
1
2
3
4
Done!
start = 25
end = 50
print("Prime numbers between", start, "and", end, "are:")
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
num1, num2 = 0, 1
print("Fibonacci sequence:")
for i in range(10):
num1 = num2
num2 = res
Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34
num = 5
factorial = 1
if num < 0:
print("Factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
factorial = factorial * i
print("The factorial of", num, "is", factorial)
num = 76542
reverse_number = 0
print("Given Number ", num)
while num > 0:
reminder = num % 10
reverse_number = (reverse_number * 10) + reminder
num = num // 10
print("Revere Number ", reverse_number)
Given Number 76542
Revere Number 24567
my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
for i in my_list[1::2]:
print(i, end=" ")
20 40 60 80 100
input_number = 6
for i in range(1, input_number + 1):
print("Current Number is :", i, " and the cube is", (i * i * i))
n = 5
start = 2
sum_seq = 0
start = start * 10 + 2
print("\nSum of above series is:", sum_seq)
2+22+222+2222+22222+
Sum of above series is: 24690
# Exercise 1: Create a function in Python
# Write a program to create a function that takes two arguments, name
and age, and print their value.
Name("Ayush", 20)
Ayush 20
def func1(*args):
for i in args:
print(i)
20
40
60
80
100
(50, 30)
# It should accept the employee’s name and salary and display both.
# If the salary is missing in the function call then assign default
value 9000 to salary
show_employee("Ayush", 12000)
show_employee("Raj")
add = addition(a, b)
return add + 5
20
# Exercise 6: Create a recursive function
# Write a program to create a recursive function to calculate the sum
of numbers from 0 to 10.
def addition(num):
if num:
res = addition(10)
print(res)
55
display_student("Ayush", 20)
Ayush 20
Raj 20
[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
24
lists
March 8, 2025
numbers = [1, 2, 3, 4, 5, 6, 7]
# result list
res = []
for i in numbers:
res.append(i * i)
print(res)
1
[6]: # Exercise 5: Iterate both lists simultaneously
10 400
20 300
30 200
40 100
list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
list1[2][2].append(7000)
print(list1)
[10, 20, [300, 400, [5000, 6000, 7000], 500], 30, 40]
list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
sub_list = ["h", "i", "j"]
list1[2][1][2].extend(sub_list)
print(list1)
['a', 'b', ['c', ['d', 'e', ['f', 'g', 'h', 'i', 'j'], 'k'], 'l'], 'm', 'n']
[12]: # EXERCISE 9 --> REPLACE ITS ITEMS FROM THE NEW VALUE IF FOUND
2
list1 = [5, 10, 15, 20, 25, 50, 20]
[13]: # Exercise 10: Remove all occurrences of a specific item from a list.
[ ]:
3
# Exercise 1: Convert two lists into a dictionary
{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
# Exercise 3: Print the value of key ‘history’ from the below dict
sampleDict = {
"class": {
"student": {
"name": "Mike",
"marks": {
"physics": 70,
"history": 80
}
}
}
}
print(sampleDict['class']['student']['marks']['history'])
80
# Individual data
print(res["Kelly"])
{'Kelly': {'designation': 'Developer', 'salary': 8000}, 'Emma':
{'designation': 'Developer', 'salary': 8000}}
{'designation': 'Developer', 'salary': 8000}
sampleDict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york" }
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New york"
}
# Keys to remove
keys = ["name", "salary"]
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New york"
}
sample_dict['location'] = sample_dict.pop('city')
print(sample_dict)
sample_dict = {
'Physics': 82,
'Math': 65,
'history': 75
}
print(min(sample_dict, key=sample_dict.get))
Math
sample_dict = {
'emp1': {'name': 'Jhon', 'salary': 7500},
'emp2': {'name': 'Emma', 'salary': 8000},
'emp3': {'name': 'Brad', 'salary': 6500}
}
sample_dict['emp3']['salary'] = 8500
print(sample_dict)
sample_set.update(sample_list)
print(sample_set)
print(set1.intersection(set2))
print(set1.union(set2))
# Exercise 4: Update the first set with items that don’t exist in the
second set
set1 = {10, 20, 30}
set2 = {20, 40, 50}
set1.difference_update(set2)
print(set1)
{10, 30}
{50, 40}
print(set1.symmetric_difference(set2))
{20, 70, 10, 60}
if set1.isdisjoint(set2):
print("Two sets have no items in common")
else:
print("Two sets have items in common")
print(set1.intersection(set2))
set1.symmetric_difference_update(set2)
print(set1)
# Exercise 9: Remove items from set1 that are not common to both set1
and set2
set1.intersection_update(set2)
print(set1)
# Exercise 1: Reverse the tuple
print(tuple1[1][1])
20
tuple1= (50, )
print(tuple1)
(50,)
a, b, c, d = tuple1
print(a)
print(b)
print(c)
print(d)
10
20
30
40
(11, 22)
(99, 88)
# Exercise 10: Check if all items in the tuple are the same
def check(t):
return all(i == t[0] for i in t)
True
# Exercise 1
# Create a string made of the first, middle and last character
str1 = 'Ayush'
print("Given string is: ", str1)
first_character = str1[0]
length_of_the_string = len(str1)
middle_index_of_the_string = int(length_of_the_string / 2)
print("String with first middle and the last character is: ",
first_character)
# Given two strings, s1 and s2. Write a program to create a new string
s3 by appending s2 in the middle of s1.
s1 = "Ault"
s2 = "Kelly"
lenght_of_the_string_s1 = len(s1)
middle_index_of_the_s1 = int(lenght_of_the_string_s1/2)
get_char_from_zero_to_middle = x = s1[:middle_index_of_the_s1:]
get_char_from_zero_to_middle = get_char_from_zero_to_middle + s2
get_char_from_zero_to_middle = get_char_from_zero_to_middle +
s1[middle_index_of_the_s1:]
print(get_char_from_zero_to_middle)
AuKellylt
# Exercise 3: Create a new string made of the first, middle, and last
characters of each input string
# Given two strings, s1 and s2, write a program to return a new string
made
# of s1 and s2’s first, middle, and last characters.
s1 = "America"
s2 = "Japan"
str1 = "PyNaTive"
lower = []
upper = []
lower.append(char)
else:
upper.append(char)
sorted_str = ''.join(lower + upper)
print('Result:', sorted_str)
Result: yaivePNT
str1 = "P@#yn26at^&i5ve"
char_count = 0
digit_count = 0
symbol_count = 0
if char.isalpha():
char_count += 1
elif char.isdigit():
digit_count += 1
else:
symbol_count += 1
# Given two strings, s1 and s2. Write a program to create a new string
s3 made of the first char of s1,
# then the last char of s2, Next, the second char of s1 and second
last char of s2, and so on.
# Any leftover chars go at the end of the result.
s1 = "Abc"
s2 = "Xyz"
s1_length = len(s1)
s2_length = len(s2)
s2 = s2[::-1]
for i in range(length):
if i < s1_length:
result = result + s1[i]
if i < s2_length:
result = result + s2[i]
print(result)
AzbycX
s1 = "Yn"
s2 = "PYnative"
flag = string_balance_test(s1, s2)
print("s1 and s2 are balanced:", flag)
temp_str = str1.lower()
# use count function
count = temp_str.count(sub_string.lower())
print("The USA count is:", count)
# Given a string s1, write a program to return the sum and average of
the digits that appear in the string,
# ignoring all other characters.
input_str = "PYnative29@#8496"
total = 0
cnt = 0
for char in input_str:
if char.isdigit():
total += int(char)
cnt += 1
str1 = "Apple"
char_dict = dict()
char_dict[char] = count
print('Result:', char_dict)
str1 = "PYnative"
print("Original String is:", str1)
str1 = str1[::-1]
print("Reversed String is:", str1)
index = str1.rfind("Emma")
print("Last occurrence of Emma starts at index:", index)
Original String is: Emma is a data scientist who knows Python. Emma
works at google.
Last occurrence of Emma starts at index: 43
str1 = "Emma-is-a-data-scientist"
print("Original String is:", str1)
# split string
sub_strings = str1.split("-")
if s:
res_list.append(s)
print(res_list)
import string
print(res)
res = []
temp = str1.split()
replace_char = '#'
March 8, 2025
import re
email_validate_pattern = r"^\S+@\S+\.\S+$"
re.match(email_validate_pattern, "[email protected]")
extract_email_pattern = r"\S+@\S+\.\S+"
import re
1
words_pattern = "^[0-9]{5}(?:-[0-9]{4})?$"
re.match(words_pattern, '80001')
re.match(words_pattern, '80001-2222')
re.match(words_pattern, '800010')
[3]: ['80001']
↪note>')
[5]: ['Ayush']
import re
validate_phone_number_pattern = "^\\+?[1-9][0-9]{7,14}$"
re.match(validate_phone_number_pattern, "+12223334444") # Returns Match object
2
re.findall(extract_phone_number_pattern, 'You can reach me out at +12223334444␣
↪and +56667778888')
import re
import re
# Validate number
number_pattern = "^\\d+$"
re.match(number_pattern, '42') # Returns Match object
re.match(number_pattern, 'notanumber') # Returns None
[10]: ['203']
3
# The regular expression to match only words looks like this (including␣
↪compound words):
# Validate words
words_pattern = "^\\b(?:\\w|-)+\\b$"
re.match(words_pattern, 'word') # Returns Match object
re.match(words_pattern, 'pet-friendly') # Returns Match object
re.match(words_pattern, 'not a word') # Returns None
import re
[14]: ['00:00:5e:00:53:af']
4
# -----> this is the pattern "<(?:\"[^\"]*\"['\"]*|'[^']*'['\"]*|[^'\">])+>"
html_pattern = "<(?:\"[^\"]*\"['\"]*|'[^']*'['\"]*|[^'\">])+>"
re.sub(html_pattern, '', '<html><body>Hello, <b>world</b>!<br /></body></html>')
# This however does not guarantee that the date would be valid. You can also␣
↪replace \\/ with a separator you need.
import re
# Validate date
date_pattern = "^[0-9]{1,2}\\/[0-9]{1,2}\\/[0-9]{4}$"
re.match(date_pattern, '12/12/2022') # Returns Match object
[ ]:
5
untitled10
March 8, 2025
['2', '5']
1
res = re.split(r"\s", target_string)
print("All tokens:", res)
# Output ['Jessa', 'salary', 'is', '8000$']
J
8
['8', '0', '0', '0']
All tokens: ['Jessa', 'salary', 'is', '8000$']
Jessa-salary-is-8000$
[8]: import re
<class 're.Pattern'>
['251', '761', '231', '451']
['111', '212', '415']
2
[9]: import re
[10]: import re
# Target String
target_string = "Emma is a baseball player who was born on June 17"
[11]: import re
target_string = "Emma is a basketball player who was born on June 17, 1993. She␣
↪played 112 matches with scoring average 26.12 points per game. Her weight is␣
↪51 kg."
3
Found following matches
['17', '1993', '112', '26', '12', '51']
[12]: import re
['My', 'name', 'is', 'maximums', 'and', 'my', 'luck', 'numbers', 'are', '12',
'45', '78']
[13]: import re
Jessa_knows_testing_and_machine_learning
[14]: import re
('PINEAPPLE', '20')
PINEAPPLE
20
4
[15]: import re
E
Emma loves
[16]: import re
[17]: import re
# with re.I
result = re.findall(r"kelly", target_str, re.I)
print(result)
5
# Output ['KELLy', 'kelly']
# with re.IGNORECASE
result = re.findall(r"kelly", target_str, re.IGNORECASE)
print(result)
# Output ['KELLy', 'kelly']
['kelly']
['KELLy', 'kelly']
['KELLy', 'kelly']
[ ]: