0% found this document useful (0 votes)
68 views47 pages

Python Lab All

The document contains various Python programming exercises and examples, including calculations involving paper folding to reach the moon, surface area calculations of the Earth, and string manipulations for DNA sequences. It also covers algorithms for computing the arithmetic-geometric mean, Hero's method for square roots, and shuffling letters in words while preserving punctuation. Additionally, it includes sections on basic Python syntax, data types, and variable assignments.

Uploaded by

jadena5711
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)
68 views47 pages

Python Lab All

The document contains various Python programming exercises and examples, including calculations involving paper folding to reach the moon, surface area calculations of the Earth, and string manipulations for DNA sequences. It also covers algorithms for computing the arithmetic-geometric mean, Hero's method for square roots, and shuffling letters in words while preserving punctuation. Additionally, it includes sections on basic Python syntax, data types, and variable assignments.

Uploaded by

jadena5711
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/ 47

1. How many times must a sheet of paper (thickness, t = 0.

1 mm but otherwise any size


required) be folded to reach the moon (distance to Moon from Earth, d = 384, 400
km)?
import math

def folds_to_reach_moon(thickness_mm, distance_km):


distance_mm = distance_km * 1_000_000
folds = math.log2(distance_mm / thickness_mm)
return math.ceil(folds)

paper_thickness = 0.1
moon_distance = 384_400

required_folds = folds_to_reach_moon(paper_thickness, moon_distance)


print(f"Number of folds required to reach the Moon:
{required_folds}")

Number of folds required to reach the Moon: 42

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_oblate_spheroid(a, c):


e_squared = 1 - (c**2 / a**2)
e = math.sqrt(e_squared)
atanh_e = 0.5 * math.log((1 + e) / (1 - e))
S_obl = (2 * math.pi * a**2) * (1 + ((1 - e_squared) / e) *
atanh_e)
return S_obl

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)

print(f"Surface Area of the Oblate Spheroid:


{surface_area_oblate:.2f} m²")
print(f"Surface Area of the Sphere: {surface_area_sphere:.2f} m²")
print(f"Their Difference is: {surface_area_diff:.2f} m²")

Surface Area of the Oblate Spheroid: 510065621724078.94 m²


Surface Area of the Sphere: 510064471909788.25 m²
Their Difference is: 1149814290.69 m²

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}")

Fraction of G and C in the sequence: 0.58

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}")

The sequence 'TGGATCCA' is palindromic: True

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

def agm(x, y, tolerance=1e-10):


a = x
b = y

while abs(a - b) > tolerance:


a_next = (a + b) / 2
b_next = math.sqrt(a * b)
a, b = a_next, b_next

return a

x = 1
y = math.sqrt(2)
agm_value = agm(x, y)
G = 1 / agm_value

print(f"AGM(1, sqrt(2)) = {agm_value:.10f}")


print(f"Gauss's constant G = {G:.10f}")

AGM(1, sqrt(2)) = 1.1981402347


Gauss's constant G = 0.8346268417

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

def hero_method(S, initial_guess, tolerance=0.01):


x_n = initial_guess
while True:
x_next = 0.5 * (x_n + S / x_n)
if abs(x_next - x_n) < tolerance:
break
x_n = x_next
return round(x_next, 2)

S = 2117519.73
initial_guess = 2000

estimated_sqrt = hero_method(S, initial_guess)


exact_sqrt = round(math.sqrt(S), 2)

print(f"Estimated Square Root: {estimated_sqrt}")


print(f"Exact Square Root: {exact_sqrt}")

Estimated Square Root: 1455.17


Exact Square Root: 1455.17

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

1.1.1 Completed By: Sarveshwar Sharma


1.1.2 Date: August 24, 2024

Lab Session
1:00 PM to 1:55 PM & 2:00 PM to 2:55 PM at AIIT Lab in E-Block at AUR.

### 1.1.3 Write, Execute, Edit, Comments, Debug

print(“Hello world!”) # prints whatever is there within the parentheses without quotes (Given
comment)

1.1.4 How to comment with commands


# Below we are going to print a computation

print(2 + 3)
print()
%time

CPU times: total: 0 ns


Wall time: 0 ns

'''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."

1.1.5 Write, Execute, Debug, and Edit a Program


print("Hello World!") # Write and Execute
Hello World!

print("Hello Amazing World!") # Edit and Execute

Hello Amazing World!

print("Hello Amazing World) # Throws an error for debugging

Cell In[32], line 1


print("Hello Amazing World) # Throws an error for debugging
^
SyntaxError: unterminated string literal (detected at line 1)

print("Hello Amazing World again!")

Hello Amazing World again!

1.2 Variables and Operators


a = 1 # Declaring a variable 'a' holding a value of 1.
print(a) # prints the value of a stored from previous step.

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

1amity = "Amity University"


print(1amity)
Cell In[47], line 1
1amity = "Amity University"
^
SyntaxError: invalid decimal literal

amity1 = "Amity University"


print(amity1)

Amity University

_amity = "Amity University"


print(_amity)

Amity University

Multiple variables to many values


x, y, z = "Apple", "Banana", "Orange"
print(x)
print(y)
print(z)
print(x,y,z)
print(x,y,z, sep="; ", end = '!')
help(print)

Apple
Banana
Orange
Apple Banana Orange
Apple; Banana; Orange!Help on built-in function print in module
builtins:

print(*args, sep=' ', end='\n', file=None, flush=False)


Prints the values to a stream, or to sys.stdout by default.

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

1.2.1 Python Output Variables


w = "Python"
x = "is"
y = "Amazing"
z = "!"
# See the difference below in printing variables together or
individually
print(w,x,y,z)
print() # Just to enter an empty line
print(w)
print(x)
print(y)
print(z)
print() # Just to enter an empty line
print(w, end = " ")
print(x, end = " ")
print(y, end = "")
print(z)
print(w, " ")
print(x, " ")
print(y, " ")
print(z)

Python is Amazing !

Python
is
Amazing
!

Python is Amazing!
Python
is
Amazing
!

1.2.2 Data Types


# Integer data type
x = 5
print(x)
print(type(x)) # type of data type
print()
# Float data type
y = 5.2
print(y)
print(type(y)) # type of data type
print()
# Complex data type
z = 5 + 2j
print(z)
print(type(z)) # type of data type

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 Creating sequences: list, set, tuple, dictionary…. Using these


sequences, we can store multiple values in one single variable.
# Example of List
my_lyst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(my_lyst)
print(type(my_lyst)) # type of list data type

[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

a amity1 b c dataframe_columns dataframe_hash


dtypes_str get_dataframes getpass
hashlib import_pandas_safely is_data_frame json my_lyst
my_tup my_txt student w
x y z
%whos

Variable Type Data/Info


--------------------------------------------
a int 1
amity1 str Amity University
b int 2
c float 2.3
dataframe_columns function <function dataframe_colum<...>ns at
0x0000015536F75440>
dataframe_hash function <function dataframe_hash at
0x0000015536F756C0>
dtypes_str function <function dtypes_str at
0x0000015536F754E0>
get_dataframes function <function get_dataframes at
0x0000015536F75620>
getpass module <module 'getpass' from
'C<...>conda3\\Lib\\getpass.py'>
hashlib module <module 'hashlib' from
'C<...>conda3\\Lib\\hashlib.py'>
import_pandas_safely function <function import_pandas_s<...>ly at
0x00000155348C71A0>
is_data_frame function <function is_data_frame at
0x00000155348C7740>
json module <module 'json' from 'C:\\<...>\
Lib\\json\\__init__.py'>
my_lyst list n=10
my_tup tuple n=10
my_txt str This is the second day
of<...>Python for Data Analysis'
student int 25
w str Python
x int 5
y float 5.2
z complex (5+2j)

%%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>

1.2.4 Operators in Python


Arithmetic Operator “+”
a = 5
b = 3
print(a + b)
print()
a = 5
b = 3.2
print(a + b)
print()
a = 5
b = 3 + 2j
print(a + b)
print()
print()
a = "hello"
b = "students"
print(a + b) # here + serves as a concatenation agent
a = "hello "
b = "students"
print(a + b) # here + serves as a concatenation agent

8.2

(8+2j)

hellostudents
hello students

Arithmetic Operator “-”


# Integer Subtraction
a = 5
b = 3
print(a - b) # Output: 2
print()

# Floating-point Subtraction
a = 1.4
b = 3.2
print(a - b) # Output: -1.8
print()

# Complex Number Subtraction


a = 5 + 2j
b = 3 + 2j
print(a - b) # Output: (2+0j)
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

Arithmetic Operator “*”


a = 5
b = 3
print(a * b)
print()
a = 1.4
b = 3.2
print(a * b)
print()
a = 5 + 2j
b = 3 + 2j
print(a * b)
print()
a = "hello"
b = "students"
print(a * b)
# Error here because strings can not be multiplied

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)

TypeError: can't multiply sequence by non-int of type 'str'


Arithmetic Operator "/"
a = 5
b = 3
print(a / b)
print()
a = 1.4
b = 3.2
print(a / b)
print()
a = 5 + 2j
b = 3 + 2j
print(a / b)
print()
a = "hello"
b = "students"
print(a / b) # Error here because strings can not be divided

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)

TypeError: unsupported operand type(s) for /: 'str' and 'str'

Quotient Operator “//” (Quotient) # Floor Division


a = 5
b = 3
print(a // b)
print()
a = 1.4
b = 3.2
print(a // b)
print()
a = 5 + 2j
b = 3 + 2j
print(a // b)
1

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)

TypeError: unsupported operand type(s) for //: 'complex' and 'complex'

Modulus Operator “%” (Remainder)


a = 5
b = 3
print(a % b)
print()
a = 1.4
b = 3.2
print(a % b)
print()

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)

TypeError: unsupported operand type(s) for %: 'complex' and 'complex'

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)

TypeError: not all arguments converted during string formatting

Exponent Operator (**)


a = 5
b = 3
print(a ** b)
print()
a = 1.4
b = 3.2
print(a ** b)
print()
a = 5 + 2j
b = 3 + 2j
print(a ** b)
print()
x_big = 412678943
print(x_big ** 78)

125

2.9350108709895886

(-14.750673611547551-71.45479955199288j)

1041741922129635665844108442483420492399535281740556063722091701390764
2459254307097531870068843294176811886951271662925229409074370116868301
3487917986244759137483353611289364298317075142842403992362250937523464
3815334368279221154336717420580320924423768568338470634503231610453116
9406005081518716984605479619669053648482265478378929207927624677177974
1174336134739000028419039712397866038221322200876748345818039196826282
9367328570296161083661323679540010076202356363185734140481105315652407
5517714726034499953254136029520646413643650406849129340325179251593070
7732640875941915017073705451113011355225394844015697561846135016483938
7303309687321080805420017579546722352605249

# Solving a big arithmetic equation


y_big = ((879*98)+(87.654/99)+(765**56)+(1267543-654794))/2
print(y_big)
1.5276025439380492e+161

Boolean Operators (True or False)


a = 5
b = 3
c = 5
print(a == b)
print(a < b)
print(a > b)
print(a == c)
print(a < c)
print(a > c)
print(b == c)
print(b < c)
print(b > c)

False
False
True
True
False
False
False
True
False

Logical Operators (AND, OR, and NOT)


a = True
b = False
# AND Operator
print(a and b)
b = True
print(a and b)

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

1.2.5 Types of the Python Functions


Built-in functions
import builtins
dir(__builtins__) # all 68 built-in functions and everything in the
module- builtins- here

['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']

# Shows only fucntions within- builtins- module here


import types
builtin_function_names = [name for name, obj in vars(builtins).items()
if isinstance(obj, types.BuiltinFunctionType)]
print(builtin_function_names)

['__build_class__', '__import__', 'abs', 'all', 'any', 'ascii', 'bin',


'breakpoint', 'callable', 'chr', 'compile', 'delattr', 'dir',
'divmod', 'eval', 'exec', 'format', 'getattr', 'globals', 'hasattr',
'hash', 'hex', 'id', 'isinstance', 'issubclass', 'iter', 'aiter',
'len', 'locals', 'max', 'min', 'next', 'anext', 'oct', 'ord', 'pow',
'print', 'repr', 'round', 'setattr', 'sorted', 'sum', 'vars', 'open']

Recursive functions We Will learn this later.

Lambda functions We Will learn this later.

User-defined functions We Will learn this later.


# abs function
print(abs(5))
print(abs(-5))
print(abs(-6.345))
print(abs(1+2j))

5
5
6.345
2.23606797749979

# binary (bin) function (Works only for integers)


print(bin(37))
print(bin(-2))
#print(bin(-3.5))
#print(bin(3+4j))

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

1 MCS345 Python - Lab 03

1.1 Course Instructor: Dr. Shatrughan Singh

1.1.1 Completed By: Sarveshwar Sharma

1.1.2 Date: August 28, 2024


# Ask the user to enter a word
word = input("Enter a word: ")

# Print the word 30 times, each on a separate line


for _ in range(30):
print(word)

Enter a word: 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

# Ask the user to enter a word


word = input("Enter a word: ")

# Print the word 100 times on the same line


print(word * 100)

Enter a word: 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 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 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 python python python python python python python
python

# Use a for loop to print numbers from 9 to 90 on the same line


separated by spaces
for number in range(9, 91):
print(number, end=' ')

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

# Use a for loop to print the sequence from 39 to 4 in descending


order on the same line separated by spaces
for number in range(39, 3, -1):
print(number, end=' ')

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

# Ask the user to enter a number


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

# Print the letter 'A' the specified number of times on the same
line
print('A' * number)

Enter a number: 28

AAAAAAAAAAAAAAAAAAAAAAAAAAAA

# Use a for loop to ask for 10 numbers


for i in range(10):
# Ask the user to enter a number
number = int(input(f"Enter number {i+1}: "))

# Calculate the square of the number


square = number ** 2

# Print the square of the number


print(f"The square of {number} is {square}")

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

Enter number 10: 10

The square of 10 is 100

import math

# Ask the user to specify the number of iterations


iterations = int(input("Enter the number of iterations: "))

# Initialize variables for the approximation


pi_approximation = 0
sign = 1

# Use a for loop to calculate the approximation of π


for i in range(iterations):
term = sign / (2 * i + 1)
pi_approximation += term
sign *= -1 # Alternate sign for each term

# Multiply the result by 4 to get the approximation of π


pi_approximation *= 4

# Get the value of π from the math module


pi_actual = math.pi

# Display the results


print(f"Approximated value of π using {iterations} iterations:
{pi_approximation}")
print(f"Actual value of π from the math module: {pi_actual}")

Enter the number of iterations: 10

Approximated value of π using 10 iterations: 3.0418396189294032


Actual value of π from the math module: 3.141592653589793
quote = "Didn’t Hamlet say ‘‘To be or not to be’’?"
print(quote)

Didn’t Hamlet say ‘‘To be or not to be’’?

# Ask the user to enter a string


user_string = input("Enter a string of at least six characters: ")

# Check if the string has at least 6 characters


if len(user_string) < 6:
print("The string must be at least six characters long.")
else:
# (a) The length of the string
print("The length of the string is:", len(user_string))

# (b) The second character of the string


print("The second character is:", user_string[1])

# (c) The last character of the string


print("The last character is:", user_string[-1])

# (d) The first five characters of the string


print("The first five characters are:", user_string[:5])

# (e) The last two characters of the string


print("The last two characters are:", user_string[-2:])

# (f) The string backwards


print("The string backwards is:", user_string[::-1])

# (g) Every character except the last one


print("The string except the last character is:", user_string[:-
1])

# (h) Every character except the first and last one


print("The string except the first and last character is:",
user_string[1:-1])

# (i) Check if the string contains a lowercase 'a'


if 'a' in user_string:
print("The index of the first 'a' is:",
user_string.index('a'))
else:
print("There is no lowercase 'a' in the string.")

# (j) The string in all caps


print("The string in all caps is:", user_string.upper())

# (k) The string with every space replaced by an underscore


print("The string with spaces replaced by underscores is:",
user_string.replace(' ', '_'))
Enter a string of at least six characters: asdfghjkil
The length of the string is: 10
The second character is: s
The last character is: l
The first five characters are: asdfg
The last two characters are: il
The string backwards is: likjhgfdsa
The string except the last character is: asdfghjki
The string except the first and last character is: sdfghjki
The index of the first 'a' is: 0
The string in all caps is: ASDFGHJKIL
The string with spaces replaced by underscores is: asdfghjkil

# Ask the user to enter a programming language


language = input("Enter a programming language: ")

# Convert the input to lowercase and check if it is 'python'


if language.lower() == 'python':
print("You entered Python.")

Enter a programming language: PyThON


You entered Python.

# Ask the user to enter a string


user_string = input("Enter a string: ")

# Check if the string contains any periods, commas, or semicolons


if '.' in user_string or ',' in user_string or ';' in user_string:
print("There is some punctuation.")
else:
# Count the number of spaces in the string
space_count = user_string.count(' ')
print("Number of spaces in the string:", space_count)

Enter a string: df;


There is some punctuation.

# Ask the user to enter a string


user_string = input("Enter a string: ")

# Check the length of the string


if len(user_string) >= 5:
# Create a new string with the first five characters plus three
asterisks
new_string = user_string[:5] + '***'
print("New string:", new_string)
else:
# Add exclamation marks to make the string length up to five
new_string = user_string.ljust(5, '!')
print("New string:", new_string)
Enter a string: kj
New string: kj!!!

# Ask the user to enter their first and last names


full_name = input("Enter your first and last names (e.g., John Doe):
")

# Split the full name into first and last names


first_name, last_name = full_name.split()

# Ask the user for their gender


gender = input("Enter your gender (male/female): ").strip().lower()

# Ask the user if they prefer formal or informal address


address_preference = input("Do you prefer formal or informal address?
(formal/informal): ").strip().lower()

# Determine the appropriate salutation based on gender and address


preference
if address_preference == 'formal':
if gender == 'male':
salutation = f"Mr. {last_name}"
elif gender == 'female':
salutation = f"Ms. {last_name}"
else:
salutation = f"{last_name}" # Default if gender is not
recognized
else:
salutation = first_name

# Print the greeting


print(f"Hello, {salutation}!")

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!

# Ask the user to enter their name in lowercase


name = input("Enter your first name in lowercase: ")

# Initialize an empty string for the transformed name


transformed_name = ''

# Iterate over each character in the name


for char in name:
# Check if the character is 'z', which should wrap around to 'a'
if char == 'z':
transformed_name += 'a'
else:
# Get the next character in the alphabet
transformed_name += chr(ord(char) + 1)

# Print the transformed name


print("Transformed name:", transformed_name)

Enter your first name in lowercase: shubh


Transformed name: tivci
# Open the file and read its content using read() method
with open('myfile.txt', 'r') as file:
content = file.read()

# Print the content


print(content)

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

# Open the file for reading


with open('myfile.txt', 'r') as file:
# Read all lines from the file
lines = file.readlines()

# Get the number of lines


num_lines = len(lines)

# Print the number of lines


print(f"Number of lines: {num_lines}")

Number of lines: 5

# Open the file for reading


with open('myfile.txt', 'r') as file:
count = 0

# Read each line in the file


for line in file:
words = line.split()
# Loop through each word and check the length using indexing
for word in words:
if len(word) == 6:
count += 1
# Print the result
print("Number of six-letter words:", count)

Number of six-letter words: 1

# Open the file and read lines as integers


with open('numbers.txt', 'r') as file:
numbers = [int(line.strip()) for line in file]

# Calculate the average


average = sum(numbers) / len(numbers)

# Print the result


print(f"Average value of the integers: {average}")

Average value of the integers: 5.833333333333333

import os

# Get the list of all items in the current working directory


items = os.listdir('.')

# Print each item


for item in items:
print(item)

python lab 1 shubhangi saklani.ipynb


.atom
.bash_history
.conda
.condarc
.continuum
.gitconfig
.idlerc
.ipynb_checkpoints
.ipython
.jupyter
.matplotlib
.packettracer
.VirtualBox
.vscode
3D Objects
anaconda3
AppData
Application Data
arr,nph.npy
arr.nph.npy
bluej
Cisco Packet Tracer 7.3.0
Cisco Packet Tracer 8.2.2
Contacts
Cookies
copy
Creative Cloud Files
csvmergeF.csv
csvmergeF.xlsx
Customer Segmentation.csv
Desktop
Diamonds.csv
dimagkarab.ipynb
dir
Documents
dos
Downloads
Favorites
form.html
git.ipynb
Ice Cream.csv
K mean clustring .ipynb
kartik.html
lab 1 (shubhangi saklani).ipynb
Lab 1.ipynb
leaner regression.ipynb
Links
linux
linux.txt
list.html
Loan Eligibility Prediction.csv
loan eligibility.ipynb
Local Settings
lunix
mat.lip pandas real data.ipynb
matploitlib.ipynb
merge.xlsx
merging.py
Microsoft
mkdir
move
Music
My Documents
myfile.txt
NetHood
NTUSER.DAT
ntuser.dat.LOG1
ntuser.dat.LOG2
NTUSER.DAT{a2332f18-cdbf-11ec-8680-002248483d79}.TM.blf
NTUSER.DAT{a2332f18-cdbf-11ec-8680-
002248483d79}.TMContainer00000000000000000001.regtrans-ms
NTUSER.DAT{a2332f18-cdbf-11ec-8680-
002248483d79}.TMContainer00000000000000000002.regtrans-ms
ntuser.ini
numbers.txt
OneDrive
pandas.ipynb
password.ipynb
password.py
Pictures
practical
PrintHood
pro.py
processedIDS.csv
python lab 2 shubhangi saklani.ipynb
Recent
roc curve.ipynb
Saved Games
Searches
SendTo
Shubhangi-saklani-lab-03.ipynb
shubhangi-saklani-lab-04.ipynb
shubhangi-saklani-lab-05.ipynb
shubhu
shubhuProject
Start Menu
Templates
total_food_sales.xlsx
Tracing
unix
Untitled Folder
Untitled.ipynb
Untitled1.ipynb
Untitled10.ipynb
Untitled11.ipynb
Untitled12.ipynb
Untitled13.ipynb
Untitled14.ipynb
Untitled15.ipynb
Untitled2.ipynb
Untitled3.ipynb
Untitled4.ipynb
Untitled5.ipynb
Untitled6.ipynb
Untitled7.ipynb
Untitled8.ipynb
Untitled9.ipynb
Videos
VirtualBox VMs
vobfus1.csv
vulnerablity task .ipynb
vulnerablity.py
vul_tool.ipynb
wekafiles

import os

# Prompt the user for a filename


filename = input("Enter the filename: ")

# Check if the file exists


if os.path.exists(filename):
# Open and read the file contents
with open(filename, 'r') as file:
contents = file.read()
print(contents)
else:
# Print an error message if the file does not exist
print("Error: The file does not exist.")

Enter the filename: numbers.txt


5
2
4
6
8
10

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

# Print the longest line


print("Longest line:")
print(longest_line.strip())

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)

for j in range(1, i):


row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j]

# Add the row to the triangle


triangle.append(row)

return triangle

def display_pascals_triangle(triangle):
rows = len(triangle)
for i, row in enumerate(triangle):
print(' ' * (rows - i), ' '.join(map(str, row)))

# Input number of rows


rows = int(input("Enter the number of rows: "))
triangle = generate_pascals_triangle(rows)
display_pascals_triangle(triangle)

Enter the number of rows: 5

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

1. The factorial of a positive integer n, fact(n), is defined recursively as follows:

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)}")

Enter a positive integer: 4

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}")

The smallest n whose factorial is not divisible by the sum of its


digits is: 432

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.

1. Write a recursive function that expects a pathname as an argument. The pathname


can be either the name of a file or the name of a directory. If the pathname refers to a
file, its name is displayed, followed by its contents. Otherwise, if the pathname refers
to a directory, the function is applied to each name in the directory. Test this function
in a new program.
import os

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.")

# Test the function


test_path = input("Enter the path of a file or directory: ")
recursive_list(test_path)

Enter the path of a file or directory: FILE.TXT

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]

# Create a dictionary to store the counts


counts = {}

# Loop through each element in the list


for element in lst:
if element in counts:
counts[element] += 1
else:
counts[element] = 1

# Print the occurrences of each element


for element, count in counts.items():
print(f"{element} occurs {count} time{'s' if count > 1 else
''}")

5 occurs 3 times
7 occurs 2 times
2 occurs 1 time
9 occurs 1 time

# Function to check if a number is prime


def is_prime(num):
if num <= 1: # Numbers less than or equal to 1 are not prime
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True

# List to check for prime numbers


list1 = [3, 17, 9, 2, 4, 8]

# Create a new list with True/False values depending on whether


elements are prime
result = [is_prime(x) for x in list1]

# Display the result


print("List1 =", result)
List1 = [True, True, False, True, False, False]

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)

Output Tuple: ('Hello', 'You', 'Python?')

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)

Output Tuple: (20, 40, 60)

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

# Iterate through the dictionary items


for key, values in dictionary.items():
# Check if the current list of values is longer than the
previous maximum
if len(values) > max_length:
max_key = key
max_length = len(values)

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'

Key with the largest number of values: C

def Count_Each_vowel(input_string):
# Convert the string to uppercase to handle case insensitivity
input_string = input_string.upper()

# Initialize a dictionary to store counts of vowels


vowel_counts = {'A': 0, 'E': 0, 'I': 0, 'O': 0, 'U': 0}
# Iterate over each character in the string
for char in input_string:
# Check if the character is a vowel
if char in vowel_counts:
# Increment the count for that vowel
vowel_counts[char] += 1

# Remove vowels with a count of 0


vowel_counts = {k: v for k, v in vowel_counts.items() if v > 0}

return vowel_counts

# Example usage:
print(Count_Each_vowel("This is a test sentence")) # Output should
be {'I': 3, 'A': 1, 'E': 4}

{'A': 1, 'E': 4, 'I': 2}


import tkinter as tk

# Create the main window


window = tk.Tk()
window.title("Circle with Text")

# Set canvas dimensions


canvas_width = 300
canvas_height = 300

# Create a canvas
canvas = tk.Canvas(window, width=canvas_width, height=canvas_height,
bg="white")
canvas.pack()

# Define circle parameters


circle_center_x = 150
circle_center_y = 150
circle_radius = 100

# Draw the circle filled with gray color


canvas.create_oval(
circle_center_x - circle_radius, # Top-left x
circle_center_y - circle_radius, # Top-left y
circle_center_x + circle_radius, # Bottom-right x
circle_center_y + circle_radius, # Bottom-right y
fill="gray", outline="black"
)

# Add text inside the circle


canvas.create_text(circle_center_x, circle_center_y, text="Circle!",
fill="white", font=("Arial", 20))

# Run the application


window.mainloop()

import tkinter as tk

def draw_squares(canvas, start_x, start_y, side_length, gap, count):


"""Draw multiple squares using a for loop."""
for i in range(count):
x0 = start_x + (side_length + gap) * i # Top-left x
y0 = start_y # Top-left y
x1 = x0 + side_length # Bottom-right x
y1 = y0 + side_length # Bottom-right y

# Draw a square with alternating colors


color = "blue" if i % 2 == 0 else "red"
canvas.create_rectangle(x0, y0, x1, y1, fill=color,
outline="black")
# Create the main window
window = tk.Tk()
window.title("Four Squares")

# Set canvas dimensions


canvas_width = 400
canvas_height = 200

# Create a canvas
canvas = tk.Canvas(window, width=canvas_width, height=canvas_height,
bg="white")
canvas.pack()

# Draw squares using the function


draw_squares(canvas, start_x=20, start_y=50, side_length=50, gap=10,
count=4)

# Run the application


window.mainloop()

import tkinter as tk
import math

def draw_hexagon(canvas, center_x, center_y, radius, fill_color):


"""Draw a hexagon on a canvas."""
points = []
for i in range(6): # Hexagon has 6 sides
angle = math.radians(i * 60) # 60 degrees for each angle
x = center_x + radius * math.cos(angle) # x-coordinate
y = center_y + radius * math.sin(angle) # y-coordinate
points.append(x)
points.append(y)

# Create the hexagon with the computed points


canvas.create_polygon(points, fill=fill_color, outline="black")

# Create the main window


window = tk.Tk()
window.title("Hexagon")

# Set canvas dimensions


canvas_width = 400
canvas_height = 400

# 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")

# Run the application


window.mainloop()

import turtle
import math

def drawCircle(t, center_x, center_y, radius):


"""
Draw a circle using a Turtle object, given its center coordinates
and radius.

:param t: Turtle object


:param center_x: x-coordinate of the circle's center
:param center_y: y-coordinate of the circle's center
:param radius: Radius of the circle
"""
# Move the Turtle to the starting position without drawing
t.penup()
t.goto(center_x, center_y - radius) # Start at the bottom of the
circle
t.pendown()

# Calculate the distance to move for each step


step_distance = 2.0 * math.pi * radius / 120.0 # Circumference
divided into 120 parts

# Draw the circle by turning 3 degrees and moving the step


distance
for _ in range(120):
t.forward(step_distance)
t.left(3) # Turn 3 degrees

# Set up the turtle environment


screen = turtle.Screen()
screen.setup(width=600, height=600)
screen.title("Draw Circle with Turtle")

# Create a turtle object


my_turtle = turtle.Turtle()
my_turtle.speed(0) # Set maximum drawing speed

# Draw a circle with specified center and radius


drawCircle(my_turtle, center_x=0, center_y=0, radius=100)

# Wait for the user to close the window


turtle.done()

You might also like