Python Lab All
Python Lab All
paper_thickness = 0.1
moon_distance = 384_400
1. The World Geodetic System (WGS) is a set of international standards for describing
the shape of the Earth. In the latest WGS-84 revision, the Earth’s geoid is
approximated to
reference ellipsoid that takes the form of an oblate spheroid with semi-major and
semi-min r axes a = 6378137.0 m and c = 6356752.314245 m respective y. Use the
formula for the surface area of an oblate sphero The surface area of an oblate
spheroid ( S_{\text{obl}} ) is given by:
( )
2
2 1− e
Sobl =2 π a 1+ ⋅ atanh ( e ) ,
e
where
2
2 c
e =1 − 2
.
a
to calculate the surface area of this reference ellipsoid and compare it with the surface area
of the Earth assumed to be a sphere with radius 6371 km. 1 − c 2 a 2 ,
import math
def calculate_surface_area_sphere(radius):
S_sphere = 4 * math.pi * radius**2
return S_sphere
a = 6378137.0
c = 6356752.314245
radius_sphere = 6371000.0
surface_area_oblate = calculate_surface_area_oblate_spheroid(a, c)
surface_area_sphere = calculate_surface_area_sphere(radius_sphere)
surface_area_diff = calculate_surface_area_oblate_spheroid(a, c) -
calculate_surface_area_sphere(radius_sphere)
1. (a) Given a string representing a base-pair sequence (i.e., containing only the letters
A, G, C and T), determine the fraction of G and C bases in the sequence. (Hint: strings
have a count method, returning the number of occurrences of a substring.)
(b) Using only string methods, devise a way to determine if a nucleotide sequence is a
palindrome in the sense that it is equal to its own complementary sequence read backward.
For example, the sequence TGGATCCA is palindromic because its complement is ACCTAGGT
which is the same as the original sequence backward. The complementary base pairs are (A,
T) and (C, G).
def gc_fraction(sequence):
g_count = sequence.count('G')
c_count = sequence.count('C')
total_bases = len(sequence)
gc_count = g_count + c_count
fraction = gc_count / total_bases if total_bases > 0 else 0
return fraction
sequence = "AGCTAGCGTACG"
fraction_gc = gc_fraction(sequence)
print(f"Fraction of G and C in the sequence: {fraction_gc:.2f}")
def complement(base):
"""Returns the complementary base."""
if base == 'A':
return 'T'
elif base == 'T':
return 'A'
elif base == 'C':
return 'G'
elif base == 'G':
return 'C'
else:
return base
def is_palindrome(sequence):
complementary = ''.join(complement(base) for base in sequence)
return sequence == complementary[::-1]
sequence_palindrome = "TGGATCCA"
is_palindrome = is_palindrome(sequence_palindrome)
print(f"The sequence '{sequence_palindrome}' is a palindrome:
{is_palindrome}")
1. Write a while loop to calculate the arithmetic-geometric mean (AGM) of two positive
real numbers, x and y, defined as the limit of the sequences
1
a n+1= ( an +bn )
2
b n+1=√ p ⋅an ⋅b n
starting with a0 = x, b0 = y. Both sequences converge to the same number, denoted agm (x,
y). Use your loop to determine Gauss’s constant,
1
G=
agm ( 1 , √ 2 )
:
import math
return a
x = 1
y = math.sqrt(2)
agm_value = agm(x, y)
G = 1 / agm_value
1. Hero’s method for calculating the square root of a number, S, is as follows: starting
with an initial guess, x0, the sequence of numbers
x n+1=
1
2(xn +
S
xn )
are successively better approximations to √S. Implement this algorithm to estimate
the square root of 2117519.73 to two decimal places and compare with the “exact”
answer provided by the math.sqrt method. For the purpose of this exercise, start with
an initial guess, x0 = 2000.
import math
S = 2117519.73
initial_guess = 2000
1. Write a program to take a string of text (words, perhaps with punctuation, separated
by spaces) and output the same text with the middle letters shuffled randomly. Keep
any punctuation at the end of words. For example, the string: Four score and seven
years ago our fathers brought forth on this continent a new nation, conceived in
liberty, and dedicated to the proposition that all men are created equal. might be
rendered: Four sorce and seevn yeras ago our fhtaers bhrogut ftroh on this cnnoientt
a new noitan, cvieecond in lbrteiy, and ddicetead to the ptosoiporin that all men are
cetaerd euaql. Hint: random.shuffle shuffles a list of items in place.
import random
import re
def shuffle_middle(word):
match = re.match(r"([a-zA-Z]+)([^\w]*)", word)
if not match:
return word
base_word, punctuation = match.groups()
if len(base_word) <= 3:
return word
middle = list(base_word[1:-1])
random.shuffle(middle)
shuffled_word = base_word[0] + ''.join(middle) + base_word[-1]
return shuffled_word + (punctuation or "")
def shuffle_text(text):
words = text.split()
shuffled_words = [shuffle_middle(word) for word in words]
return ' '.join(shuffled_words)
text = """Four score and seven years ago our fathers brought forth
on this continent a new nation, conceived in liberty, and dedicated
to the proposition that all men are created equal."""
shuffled_text = shuffle_text(text)
print(shuffled_text)
Fuor sroce and sveen yreas ago our frethas bgorhut fotrh on tihs
cetnonint a new ntaion, ccenoveid in lbrteiy, and deidcetad to the
ppoorsoiitn taht all men are cateerd eauql.
1 MCS345 Python- Lab 02
## 1.1 Course Instructor: Dr. Shatrughan Singh
Lab Session
1:00 PM to 1:55 PM & 2:00 PM to 2:55 PM at AIIT Lab in E-Block at AUR.
print(“Hello world!”) # prints whatever is there within the parentheses without quotes (Given
comment)
print(2 + 3)
print()
%time
'''A long comment can be given within three quotes. For example, here
I'm using a multiline comment. Below using a print command, I am print
the summation of two numbers, 2 and 3, respectively. '''
"A long comment can be given within three quotes. For example, here
I'm using a multiline comment. Below using a print command, I am print
the summation of two numbers, 2 and 3, respectively. "
"""A long comment can be given within three quotes. For example, here
I'm using a multiline comment. Below using a print command, I am print
the summation of two numbers, 2 and 3, respectively."""
"A long comment can be given within three quotes. For example, here
I'm using a multiline comment. Below using a print command, I am print
the summation of two numbers, 2 and 3, respectively."
b = 2
c = 2.3
print(b,c)
print("c belongs to", type(c), "class") # float type variable c
print("c belongs to", type(c), "class", "and b belongs to", type(b),
"class.") # float type variable c
2 2.3
c belongs to <class 'float'> class
c belongs to <class 'float'> class and b belongs to <class 'int'>
class.
x = "apple"
print(x) # prints the
print("x")
apple
x
student = 25
print(student)
25
Amity University
Amity University
Apple
Banana
Orange
Apple Banana Orange
Apple; Banana; Orange!Help on built-in function print in module
builtins:
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
x = y = z = "Pineapple"
print(x)
print(y)
print(z)
Pineapple
Pineapple
Pineapple
Python is Amazing !
Python
is
Amazing
!
Python is Amazing!
Python
is
Amazing
!
5
<class 'int'>
5.2
<class 'float'>
(5+2j)
<class 'complex'>
my_txt = "This is the second day of the class: 'Python for Data
Analysis'"
print(my_txt)
print(type(my_txt)) # type of data type
This is the second day of the class: 'Python for Data Analysis'
<class 'str'>
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
<class 'list'>
# Example of Tuple
my_tup = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print(my_tup)
print(type(my_tup)) # type of tuple data type
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
<class 'tuple'>
%who
%%latex
My name is Anthony Gonsalves. Here I have done some testing of latex
in Jupyter Notebook. For example, a mathematical formulae: $$
Area_{circle} = pi \times r^2 $$ where, $r$ = radius of the circle.
<IPython.core.display.Latex object>
8.2
(8+2j)
hellostudents
hello students
# Floating-point Subtraction
a = 1.4
b = 3.2
print(a - b) # Output: -1.8
print()
# String Operations
a = "hello"
b = "students"
# Instead of subtraction, you might concatenate or slice strings
print(a + " " + b) # Concatenates and adds a space in between: "Hello
students"
print(a[:2] + " " + b[:4]) # Slices and concatenates: "he stud"
-1.8000000000000003
(2+0j)
hello students
he stud
15
4.4799999999999995
(11+16j)
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[101], line 15
13 a = "hello"
14 b = "students"
---> 15 print(a * b)
1.6666666666666667
0.43749999999999994
(1.4615384615384617-0.30769230769230765j)
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[104], line 15
13 a = "hello"
14 b = "students"
---> 15 print(a / b)
0.0
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[107], line 11
9 a = 5 + 2j
10 b = 3 + 2j
---> 11 print(a // b)
a = 5 + 2j
b = 3 + 2j
print (a % b)
1.4
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[114], line 13
11 a = 5 + 2j
12 b = 3 + 2j
---> 13 print (a % b)
a = "hello"
b = "students"
print(a%b)
# Error here because strings can not be divided
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[122], line 3
1 a = "hello"
2 b = "students"
----> 3 print(a%b)
125
2.9350108709895886
(-14.750673611547551-71.45479955199288j)
1041741922129635665844108442483420492399535281740556063722091701390764
2459254307097531870068843294176811886951271662925229409074370116868301
3487917986244759137483353611289364298317075142842403992362250937523464
3815334368279221154336717420580320924423768568338470634503231610453116
9406005081518716984605479619669053648482265478378929207927624677177974
1174336134739000028419039712397866038221322200876748345818039196826282
9367328570296161083661323679540010076202356363185734140481105315652407
5517714726034499953254136029520646413643650406849129340325179251593070
7732640875941915017073705451113011355225394844015697561846135016483938
7303309687321080805420017579546722352605249
False
False
True
True
False
False
False
True
False
False
True
a = True
b = False
# OR Operator
print(a or b)
a = False
print(a or b)
True
False
a = True
b = False
# NOT Operator
print(not a)
print(not b)
False
True
['ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'BaseExceptionGroup',
'BlockingIOError',
'BrokenPipeError',
'BufferError',
'BytesWarning',
'ChildProcessError',
'ConnectionAbortedError',
'ConnectionError',
'ConnectionRefusedError',
'ConnectionResetError',
'DeprecationWarning',
'EOFError',
'Ellipsis',
'EncodingWarning',
'EnvironmentError',
'Exception',
'ExceptionGroup',
'False',
'FileExistsError',
'FileNotFoundError',
'FloatingPointError',
'FutureWarning',
'GeneratorExit',
'IOError',
'ImportError',
'ImportWarning',
'IndentationError',
'IndexError',
'InterruptedError',
'IsADirectoryError',
'KeyError',
'KeyboardInterrupt',
'LookupError',
'MemoryError',
'ModuleNotFoundError',
'NameError',
'None',
'NotADirectoryError',
'NotImplemented',
'NotImplementedError',
'OSError',
'OverflowError',
'PendingDeprecationWarning',
'PermissionError',
'ProcessLookupError',
'RecursionError',
'ReferenceError',
'ResourceWarning',
'RuntimeError',
'RuntimeWarning',
'StopAsyncIteration',
'StopIteration',
'SyntaxError',
'SyntaxWarning',
'SystemError',
'SystemExit',
'TabError',
'TimeoutError',
'True',
'TypeError',
'UnboundLocalError',
'UnicodeDecodeError',
'UnicodeEncodeError',
'UnicodeError',
'UnicodeTranslateError',
'UnicodeWarning',
'UserWarning',
'ValueError',
'Warning',
'WindowsError',
'ZeroDivisionError',
'__IPYTHON__',
'__build_class__',
'__debug__',
'__doc__',
'__import__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'abs',
'aiter',
'all',
'anext',
'any',
'ascii',
'bin',
'bool',
'breakpoint',
'bytearray',
'bytes',
'callable',
'chr',
'classmethod',
'compile',
'complex',
'copyright',
'credits',
'delattr',
'dict',
'dir',
'display',
'divmod',
'enumerate',
'eval',
'exec',
'execfile',
'filter',
'float',
'format',
'frozenset',
'get_ipython',
'getattr',
'globals',
'hasattr',
'hash',
'help',
'hex',
'id',
'input',
'int',
'isinstance',
'issubclass',
'iter',
'len',
'license',
'list',
'locals',
'map',
'max',
'memoryview',
'min',
'next',
'object',
'oct',
'open',
'ord',
'pow',
'print',
'property',
'range',
'repr',
'reversed',
'round',
'runfile',
'set',
'setattr',
'slice',
'sorted',
'staticmethod',
'str',
'sum',
'super',
'tuple',
'type',
'vars',
'zip']
5
5
6.345
2.23606797749979
0b100101
-0b10
# bytes function
print(bytes(10))
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
# character function
print(chr(99))
print(complex(2))
(2+0j)
print(complex('2'))
(2+0j)
print(complex(b))
0j
1.2.6 See usage of int(), input(), and some other built-in functions by
practice
Lab:03 – For Loops in Python
python
python
python
python
python
python
python
python
python
python
python
python
python
python
python
python
python
python
python
python
python
python
python
python
python
python
python
python
python
python
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
78 79 80 81 82 83 84 85 86 87 88 89 90
# Use a for loop to print the sequence from 2 to 102 with a step of
4 on the same line separated by spaces
for number in range(2, 103, 4):
print(number, end=' ')
2 6 10 14 18 22 26 30 34 38 42 46 50 54 58 62 66 70 74 78 82 86 90
94 98 102
39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17
16 15 14 13 12 11 10 9 8 7 6 5 4
# Use a for loop to print the first 30 perfect squares on the same
line separated by spaces
for i in range(1, 31):
print(i**2, end=' ')
1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400
441 484 529 576 625 676 729 784 841 900
# Print 10 A's
for _ in range(10):
print('A', end='')
# Print 25 B's
for _ in range(25):
print('B', end='')
# Print 15 C's
for _ in range(15):
print('C', end='')
AAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCC
# Print the letter 'A' the specified number of times on the same
line
print('A' * number)
Enter a number: 28
AAAAAAAAAAAAAAAAAAAAAAAAAAAA
Enter number 1: 1
The square of 1 is 1
Enter number 2: 2
The square of 2 is 4
Enter number 3: 3
The square of 3 is 9
Enter number 4: 4
The square of 4 is 16
Enter number 5: 5
The square of 5 is 25
Enter number 6: 6
The square of 6 is 36
Enter number 7: 7
The square of 7 is 49
Enter number 8: 8
The square of 8 is 64
Enter number 9: 9
The square of 9 is 81
import math
Enter your first and last names (e.g., John Doe): shubhangi saklani
Enter your gender (male/female): female
Do you prefer formal or informal address? (formal/informal): informal
Hello, shubhangi!
I
Love
Python
Programming
Language
# Open the file and read line by line using a for loop
with open('myfile.txt', 'r') as file:
for line in file:
print(line.strip()) # Using strip() to remove any extra
newlines
I
Love
Python
Programming
Language
Number of lines: 5
import os
import os
def find_longest_line(filename):
try:
with open(filename, 'r') as file:
longest_line = ''
for line in file:
# Update the longest line if the current line is
longer
if len(line) > len(longest_line):
longest_line = line
except FileNotFoundError:
print("Error: The file does not exist.")
# Example usage
filename = 'longest.txt' # Replace with your filename as mine is
longest.txt
find_longest_line(filename)
Longest line:
It is also the world’s most populous democracy since the time of its
independence (1947).
Lab: 06 – Functions in Python
Name: Atharva Kulkarni
1. Write a program using functions to display Pascal’s triangle.
def generate_pascals_triangle(rows):
triangle = []
for i in range(rows):
row = [1] * (i + 1)
return triangle
def display_pascals_triangle(triangle):
rows = len(triangle)
for i, row in enumerate(triangle):
print(' ' * (rows - i), ' '.join(map(str, row)))
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
fact(n) = 1,when n = 1
fact(n) = n ∗ fact(n − 1), otherwise
Define a recursive function fact that returns the factorial of a given positive integer.
def fact(n):
if n == 1:
return 1
# Recursive case: n * factorial of (n-1)
else:
return n * fact(n - 1)
# Example usage:
number = int(input("Enter a positive integer: "))
print(f"The factorial of {number} is {fact(number)}")
The factorial of 4 is 24
1. Write a function to find the smallest positive integer, n, whose factorial is not divisible
by the sum of its digits. For example, 6 is not such a number because 6! = 720 and 7 +
2 + 0 = 9 divides 720.
import math
def sum_of_digits(number):
return sum(int(digit) for digit in str(number))
def find_smallest_n():
n = 1
while True:
factorial = math.factorial(n)
digit_sum = sum_of_digits(factorial)
if factorial % digit_sum != 0:
return n
n += 1
result = find_smallest_n()
print(f"The smallest n whose factorial is not divisible by the sum
of its digits is: {result}")
1. Two functions are defined below. Which function is more meaningful and why? Can
you see any difference when you run the program?
#(a)
def showGrade(marks):
if marks >= 75.0:
print('Distinction')
elif marks >= 60.0:
print('First Division')
elif marks >= 50.0:
print('Second Division')
elif marks >= 40.0:
print('Third Division')
else:
print('Fail')
showGrade(101)
Distinction
#(b)
def showGrade(marks):
if marks >= 75.0 and marks <= 100:
print('Distinction')
elif marks >= 60.0 and marks < 75:
print('First Division')
elif marks >= 50.0 and marks < 60:
print('Second Division')
elif marks >= 40.0 and marks < 50:
print('Third Division')
elif marks >= 0.0 and marks < 40:
print('Fail')
elif marks >= 0.0 and marks < 40:
print('Fail')
else:
print('Fail')
showGrade(101)
Fail
Key Differences:
Function (a) only checks the lower bound (e.g., marks >= 75.0) without specifying the upper
limiting value which means that it will assign "Distinction" even for values greater than 100,
which may be an error. Function (b) includes both the lower and upper bounds for each grade
(e.g., marks >= 75.0 and marks <= 100). It handles cases where the marks exceed 100 or fall
below 0, ensuring the ranges are clearly defined and preventing illogical input from
producing a grade.
Function(b) is more meaningful as it contains both lower and upper bounds. It also contains a
else statement where if the marks dont match any of the given statements it is marked as
"fail". In this function all the cases including error cases are handled gracefully.
def recursive_list(pathname):
# Check if the pathname is a file
if os.path.isfile(pathname):
# Print file name and its contents
print(f"File: {pathname}")
with open(pathname, 'r') as file:
print(file.read())
# Check if the pathname is a directory
elif os.path.isdir(pathname):
print(f"Directory: {pathname}")
# Recursively apply the function to each item in the
directory
for item in os.listdir(pathname):
item_path = os.path.join(pathname, item)
recursive_list(item_path)
else:
print(f"{pathname} is not a valid file or directory.")
File: FILE.TXT
Atharva Kulkarni
A217131523067
Msc Cyber Security
Section-B
Lab: 07 – Sequences (List, Tuple, and
Dictionary) in Python
Name: Sarveeshwar sharma
LISTS
1. Write a program to count the occurrences of each element within a list
# Define the list
lst = [5, 5, 7, 2, 5, 7, 9]
5 occurs 3 times
7 occurs 2 times
2 occurs 1 time
9 occurs 1 time
def every_other_element(input_tuple):
# Slicing the tuple to get every other element starting from the
first
return input_tuple[::2]
# Example usage:
T = ('Hello', 'Are', 'You', 'Loving', 'Python?')
Output_Tuple = every_other_element(T)
print("Output Tuple:", Output_Tuple)
def elements_at_odd_indices(input_tuple):
# Slicing the tuple to get elements at odd indices
return input_tuple[1::2]
# Example usage:
T = (10, 20, 30, 40, 50, 60)
Output_Tuple = elements_at_odd_indices(T)
print("Output Tuple:", Output_Tuple)
def biggest(dictionary):
# Initialize variables to store the key with the most values and
the highest count of values
max_key = None
max_length = 0
return max_key
# Example usage:
fruits = {'A': ['Apple'], 'B': ['Banana', 'Berry'], 'C': ['Cherry',
'Citrus', 'Coconut']}
print("Key with the largest number of values:", biggest(fruits)) #
Output should be 'C'
def Count_Each_vowel(input_string):
# Convert the string to uppercase to handle case insensitivity
input_string = input_string.upper()
return vowel_counts
# Example usage:
print(Count_Each_vowel("This is a test sentence")) # Output should
be {'I': 3, 'A': 1, 'E': 4}
# Create a canvas
canvas = tk.Canvas(window, width=canvas_width, height=canvas_height,
bg="white")
canvas.pack()
import tkinter as tk
# Create a canvas
canvas = tk.Canvas(window, width=canvas_width, height=canvas_height,
bg="white")
canvas.pack()
import tkinter as tk
import math
# Create a canvas
canvas = tk.Canvas(window, width=canvas_width, height=canvas_height,
bg="white")
canvas.pack()
# Draw a hexagon
draw_hexagon(canvas, center_x=200, center_y=200, radius=100,
fill_color="yellow")
import turtle
import math