0% found this document useful (0 votes)
13 views38 pages

Examples

The document contains various Python code snippets demonstrating basic programming concepts such as arithmetic operations, string manipulations, conditionals, loops, and functions. It also includes examples of error handling and the use of built-in functions and libraries like math and random. Additionally, the document illustrates input/output operations and the use of data structures like lists and dictionaries.
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)
13 views38 pages

Examples

The document contains various Python code snippets demonstrating basic programming concepts such as arithmetic operations, string manipulations, conditionals, loops, and functions. It also includes examples of error handling and the use of built-in functions and libraries like math and random. Additionally, the document illustrates input/output operations and the use of data structures like lists and dictionaries.
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

x=7

n=17
n=4*x*(1-x)
print(n)

-168

x=1+2*3-4/5**6
print(x)

6.999744

(3*100)/60

5.0

3*100/60

5.0

4/2*8

16.0

4/(2*8)

0.25

4/2/8

0.25

"throat"+"warbler"

'throatwarbler'

'spam'*3

'spamspamspam'

'2'-'1'

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[3], line 1
----> 1 '2'-'1'

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

'eggs'*'easy'
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[12], line 1
----> 1 'eggs'*'easy'

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

'third'*'3'

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[13], line 1
----> 1 'third'*'3'

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

99//100

99/100

0.99

#type casting
99/100.0

0.99

99.0//100

0.0

1+2*3//4.0-5

-3.0

message='hello '+'there'
type (message)

str

message+1

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[21], line 1
----> 1 message+1

TypeError: can only concatenate str (not "int") to str

message+'1'

'hello there1'

num='2'+'1'
type(num)

str

result= int(num) + 1
print(result)

22

type(result)

int

num=42
float(num)

42.0

int(42.57)+1

43

str(1)+str(2)

'12'

PI=3.14

#chapter 2
True

True

type(true)

----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
Cell In[2], line 1
----> 1 type(true)

NameError: name 'true' is not defined

type(True)
bool

type('True')

str

2<3

True

7-1>=2*3

True

3==4+4

False

2!=3

True

2<3 and 4>5

False

2<3 and True

True

False or True and False

False

3 >= -1 or 8*2 > 2**4 and 9 !=3

True

2 and 2

-2**2

-4

(-2)**2

4 % 2 == 0

True

4 % 3 == 1
True

0 and False

0 and True

1 and True

True

1 and False

False

5 and True

True

0 or True

True

-1 == True

False

0==False

True

-0 == False

True

1==True

True

2==True

False

1==False

False

5==False

False
x = 5
y = 10
z = x + y
print(z)

15

if x > y:
print("x is greater than y")
elif x < y:
print("x is less than y")
else:
print("x is equal to y")

x is less than y

x=int(input("enter a number"))
if x<0:
print("the number is negative")
if x==0:
print ('the number you entered is zero')
else:
print ('the number is positive')

the number is positive

a=int(input())
b=int(input())
if b==0:
print ("the second number can't be zero")
if a%b==0:
print("the first number is divisible by the second number")
else:
print("it isn't divisible")

it isn't divisible

a='do'
if a[0]=='a':
print("a")
if a[0]=='e':
print("e")
if a[0]=='i':
print('i')
if a[0]=='o':
print("o")
if a[0]=='u':
print('u')
if a[1]=='a':
print("a")
if a[1]=='e':
print("e")
if a[1]=='i':
print('i')
if a[1]=='o':
print("o")
if a[1]=='u':
print('u')
else:
print("there is no other vowel in the string")

o
there is no other vowel in the string

y=int(input())
if y%2==0:
print('the number is even')
else:
print('the number is odd')

the number is even

x=int(input("enter your age"))


if x>=18:
print('you are eligible ')
else:
print('you aren\'t eligible' )

you aren't eligible

x=int(input("enter a number"))
if x<0:
print("the number is negative")
elif x==0:
print ('the number is zero')
else:
print ('the number is positive')

the number is negative

x=float(input ("enter a number between 0-100"))


if 0<=x<60:
print("F")
elif 60<=x<70:
print("D")
elif 70<=x<80:
print("C")
elif 80<=x<90:
print("B")
elif 90<=x<=100:
print("A")
else :
print("Invalid number")

x=int(input())
y=100
if x > 0:
if x > y:
print("x is positive & greater than y")
else:
print("x is positive & less than or equal to y")
else:
print("x is not positive")

x is positive & less than or equal to y

b=int(input())
if b%4==0:
print('the year is a leap year')
if b%100==0:
if b%400==0:
print('the year is a leap year')
else:
print('the year is not a leap year')

the year is not a leap year

x=int(input())
y=int(input())
if x>0 and y>0:
print('first quadrant')
elif x<0 and y>0:
print('second quadrant')
elif x<0 and y<0:
print('third quadrant')
elif x>0 and y<0:
print('fourth quadrant')
else:
print('it is on the axis')

fourth quadrant

#common errors
Value=78
if((Value > 0) or (Value <= 10)):
print(Value)

78
if((Value > 0) and (Value <= 10)):
print(Value)

if((Value < 0) and (Value > 10)):


print(Value)

if((1.11 - 1.10) == (2.11 - 2.10)):


print('done')

(1.11 - 1.10) == (2.11 - 2.10)

False

#Iterations
for i in range(5):
print(i)

0
1
2
3
4

count = 0
while count < 5:
print(count)
count += 1

0
1
2
3
4

for i in range(3):
for j in range(2):
print(i, j)

0 0
0 1
1 0
1 1
2 0
2 1

for i in range (1,11):


print(i)

1
2
3
4
5
6
7
8
9
10

for i in range (10):


print(i+1)

1
2
3
4
5
6
7
8
9
10

x=1
while 0<x<11:
print(x)
x=x+1

1
2
3
4
5
6
7
8
9
10

x=[1,2,5,4,5]
sum_1=0
for i in x:
sum_1=sum_1+i

print (sum_1)

17

x=[1,2,5,4,5]
sum_2=0
count=0
while count<len(x):
sum_2=x[count]+sum_2
count=count+1
print (sum_2)

17

x="hello world"
for i in x:
print(i)

h
e
l
l
o

w
o
r
l
d

x="hello world"
count=0
while count<len(x):
print(x[count])
count+=1

h
e
l
l
o

w
o
r
l
d

x=10
prod=1
count=1
while count<=x:
prod=prod*count
count +=1
print (prod)

3628800
x=10
prod=1
for i in range(1,x+1):
prod=prod*i

print(prod)

3628800

while True:
x=input()
if x=="exit":
break
else:
print (x)

e
d
r
23
45
567

a=int(input())
b=int(input())
if a/b > b/a:
count=b
else:
count=a
while count>0:
if a%count==0 and b%count==0:
print ( "the GCF is ",count)
break
else:
count-=1

the GCF is 1

x=10
while 0<=x<11:
print(x)
x=x-1

10
9
8
7
6
5
4
3
2
1
0

for i in range (1,6):


for j in range (1,6):
print (i*j,end= "\t" )
print("\n")

1 2 3 4 5

2 4 6 8 10

3 6 9 12 15

4 8 12 16 20

5 10 15 20 25

for i in range(1,8):
for j in range (1,i):
print("*", end=' ')
print("\n")

* *

* * *

* * * *

* * * * *

* * * * * *

for i in range(10):
if i == 5:
break
print(i)

0
1
2
3
4
for i in range(10):
if i % 2 == 0:
continue
print(i)

1
3
5
7
9

for i in range(10):
if i % 2 == 0:
pass # Placeholder for future code
else:
print(i)

1
3
5
7
9

sentinel = -1
number = 0
sum_3 = 0
while number != sentinel:
number = int(input("Enter a number (-1 to stop): "))
if number != sentinel:
sum_3 += number
print(f"Sum of numbers: {sum_3}")

Sum of numbers: 189

print("Hello\nWorld")

Hello
World

print("Hello\tWorld")

Hello World

print("This is a backslash: \\")

This is a backslash: \

print('It\'s a sunny day')

It's a sunny day

print("He said, \"Hello!\"")


He said, "Hello!"

print("Hello\rWorld")

World

print("Hello\bWorld")

HellWorld

print("Hello\fWorld")

HelloWorld

print("\u03B1")

print("\101")

print("\x41")

print("\a")

print("Hello\vWorld")

HelloWorld

print('Welcome to Python!')

Welcome to Python!

print("Welcome to Python!")

Welcome to Python!

print('Welcome', 'to', 'Python!')

Welcome to Python!

print('Welcome\nto\n\nPython!')

Welcome
to

Python!

print('Display "hi" in quotes')


Display "hi" in quotes

print('Display 'hi' in quotes')

Cell In[83], line 1


print('Display 'hi' in quotes')
^
SyntaxError: invalid syntax. Perhaps you forgot a comma?

print('Display \'hi\' in quotes')

Display 'hi' in quotes

print("Display the name O’Brien")

Display the name O’Brien

print("Display \"hi\" in quotes")

Display "hi" in quotes

print("""Display "hi" and 'bye' in quotes""")

Display "hi" and 'bye' in quotes

abs(-10)

10

divmod(17,3)

(5, 2)

abs(0)

enumerate(["apple","ganana","cherry"])

<enumerate at 0x204bab95b20>

max(2,4,6,7,9)

sorted([2,4,64,7,9])

[2, 4, 7, 9, 64]

all([True,True,False])

False

any([True,True,False])
True

bin(10)

'0b1010'

eval("2+2")

exec("print('hello, world!')")

hello, world!

list([1,2,6,7,8])

[1, 2, 6, 7, 8]

chr(65)

'A'

len([1,2,6,7,8])

set([1,2,2,3,3,3])

{1, 2, 3}

import math
[Link](25)

5.0

[Link](6)

720

[Link]

3.141592653589793

import random
[Link]()

0.07687738103336594

[Link](1,100)

21

[Link](["apple","ganana","cherry"])

'ganana'
import datetime
[Link]()

[Link](2024, 7, 21, 2, 40, 5, 897053)

[Link](2024,1,1)

[Link](2024, 1, 1, 0, 0)

import os
[Link]()

'c:\\Users\\tsion\\Downloads'

[Link]('c:\\Users\\tsion\\OneDrive\\Documents\\GitHub\\computer')

[Link]('c:\\Users\\tsion\\OneDrive\\Documents\\GitHub\\computer')

import math
print([Link](16))

4.0

print([Link])

3.141592653589793

print([Link](5))

120

print([Link]([Link]/2))

1.0

import random
print([Link]())

0.24723381561104252

print([Link](1, 10))

print([Link](['apple', 'banana', 'cherry']))

banana

print([Link](range(100), 5))

[93, 55, 85, 15, 59]

import datetime
now = [Link]()
print(now)
2024-07-21 02:53:33.542318

new_year = [Link](2024, 1, 1)
print(new_year)

2024-01-01 00:00:00

import os
print([Link])

nt

def print_message():
print("Hello, World!")
result = print_message()

Hello, World!

print(result)

None

print(print_message())

Hello, World!
None

def add(a, b):


return a + b
result = add(3, 5)

print(result)

def is_even(n):
return n % 2 == 0
print(is_even(4))

True

print(is_even(7))

False

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))

120
def greet(name,message="Hi"):
print (f"{message},{name}")

greet("bella")
greet("mary")
greet("bella","hello")

Hi,bella
Hi,mary
hello,bella

def describe_pet(animal_type, pet_name):


print(f"I have a {animal_type} named {pet_name}.")

describe_pet(animal_type="dog", pet_name="Rex")
describe_pet(pet_name="Mittens", animal_type="cat")

I have a dog named Rex.


I have a cat named Mittens.

def sum_numbers(*args):
return sum(args)
sum_numbers(1,2,3,3)
print(sum_numbers(1, 2, 3))
print(sum_numbers(4, 5, 6, 7))

6
22

def print_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")
print_info(name="Alice", age=30, city="New York")

name: Alice
age: 30
city: New York

x = 10 # Global variable
def print_global():
print(x)
print_global()

10

x = 10
def modify_global():
global x
x = 20
print("Before function call:", x)
modify_global()
print("After function call:", x)

Before function call: 10


After function call: 20

y = 10 # global variable
def print_local():
y = 5 # Local variable
z = 7 # Local variable
print(y,z)

print_local()

5 7

print(z)

----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
Cell In[9], line 1
----> 1 print(z)

NameError: name 'z' is not defined

print(y)

10

def example_function():
return "This will be returned"
print("This will never be printed") # Dead code
print(example_function())

This will be returned

#chapter 5
my_string="Hello, World!"

another_string = 'This is also a string.'

multiline_string = """This is a
multiline string."""

my_string[0]

'H'

my_string[-1]

'!'
my_string[7]

'W'

my_string[-2]

'd'

my_string[15]

----------------------------------------------------------------------
-----
IndexError Traceback (most recent call
last)
Cell In[7], line 1
----> 1 my_string[15]

IndexError: string index out of range

my_string[2:7]

'llo, '

my_string[:7]

'Hello, '

my_string[7:]

'World!'

my_string[::2]

'Hlo ol!'

my_string[2::2]

'lo ol!'

my_string[-2:]

'd!'

my_string[-5::-1]

'oW ,olleH'

my_string[2::3]

'l,od'

my_string[2:]

'llo, World!'
"h" in"hello world"

True

if 'Hello' in my_string:
print("found'Hello'")

found'Hello'

if 'python' not in my_string:


print("'python' not found")

'python' not found

for char in my_string:


print(char)

H
e
l
l
o
,

W
o
r
l
d
!

str1='Hello'
str2='World'
str3=str1

str1+','+str2+'!'

'Hello,World!'

str2*4

'WorldWorldWorldWorld'

str1 is str2

False

str1 is str3

True

str1[0]= "k"
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[8], line 1
----> 1 str1[0]= "k"

TypeError: 'str' object does not support item assignment

my_string="Hello, World! hello hello2 Hello"

len(my_string)

32

my_string.lower()

'hello, world! hello hello2 hello'

my_string.upper()

'HELLO, WORLD! HELLO HELLO2 HELLO'

my_string.strip()
# stirp removes white space from the string
# lstrip removes left space
# rstrip removes right space

'Hello, World! hello hello2 Hello'

my_string.replace("World","python")

'Hello, python! hello hello2 Hello'

my_string.split()

['Hello,', 'World!', 'hello', 'hello2', 'Hello']

my_string.split(',')

['Hello', ' World! hello hello2 Hello']

my_string.find("hello")

14

my_string.find("hello",15)

20

my_string.find("hello",1,3)

-1
my_string.count("Hello")

my_string.count("o")

"The sum of {0} and {1} is {2}".format(-5,6,1)

'The sum of -5 and 6 is 1'

"".join(['h','e','l','l','o'])

'hello'

my_list=[4,5,6,"apple",4.5,True,[5,6]]
print(my_list)

[4, 5, 6, 'apple', 4.5, True, [5, 6]]

my_list[0]

my_list[-1]

[5, 6]

my_list[1:4]

[5, 6, 'apple']

my_list[1:]

[5, 6, 'apple', 4.5, True, [5, 6]]

my_list[-2:]

[True, [5, 6]]

my_list[:3]

[4, 5, 6]

my_list[::2]

[4, 6, 4.5, [5, 6]]

my_list[::-1]

[[5, 6], True, 4.5, 'apple', 6, 5, 4]

my_list[::-2]
[[5, 6], 4.5, 6, 4]

my_list=[1,2,3,"apple",4.5]

my_list[0]=10
print(my_list,len(my_list))

[10, 2, 3, 'apple', 4.5] 5

my_list[1:3]=["Banana","cherry"]
print(my_list)

[10, 'Banana', 'cherry', 'apple', 4.5]

for item in my_list:


print(item)

10
Banana
cherry
apple
4.5

for index,item in enumerate(my_list):


print(f"index:{index},item:{item}")

index:0,item:1
index:1,item:2
index:2,item:3
index:3,item:apple
index:4,item:4.5

"apple" in my_list

True

"banana" not in my_list

True

my_list2=[1,1,2,3,4]
my_list+my_list2

[10, 'Banana', 'cherry', 'apple', 4.5, 1, 1, 2, 3, 4]

my_list2*2

[1, 1, 2, 3, 4, 1, 1, 2, 3, 4]

n=6
[89]*n

[89, 89, 89, 89, 89, 89]


my_list=[1,4,3,2,6]
my_list.append(8)
my_list

[1, 4, 3, 2, 6, 8]

my_list.insert(1,95)
my_list

[5, 95, 5, 5, 5, 5, 1, 5, 4, 3, 2, 6, 8]

#the same as append


my_list.insert(len(my_list),95)
my_list

[5, 95, 5, 5, 5, 5, 1, 5, 4, 3, 2, 6, 8, 95]

my_list.insert(1000,95)
my_list

[5, 95, 5, 5, 5, 5, 1, 5, 4, 3, 2, 6, 8, 95, 95]

my_list=[3,4,2,1]
my_list.extend([5,6])
my_list

[3, 4, 2, 1, 5, 6]

my_list.remove(6)
my_list

[3, 4, 2, 1, 5]

#removes element from the last element


my_list.pop()
#my_list

my_list=[3,4,2,1]
#my_list.pop(1)
my_list

[3, 4, 1]

my_list.remove(3)
my_list

[4]

my_list=[3,1,2,3,5,4,] #[apple",4.5]
my_list.index(3)
0

my_list.count(3)

my_list.sort()
my_list

[1, 2, 3, 3, 4, 5]

my_list.reverse()
my_list

[5, 4, 3, 3, 2, 1]

b=my_list.copy()
b

[5, 4, 3, 3, 2, 1]

my_list.clear()

c=my_list
c[0]=34

my_list

[34, 4, 3, 3, 2, 1]

id(c)==id(my_list)

True

my_list.clear()

my_list

[]

squares=[a**2 for a in range(1,6)]


print(squares)

[1, 4, 9, 16, 25]

even=[x for x in range(1,11) if x%2==0]


print(even)

[2, 4, 6, 8, 10]

my_tuple=(1,2,4,1,"apple",True,4.5)
t=my_tuple

my_tuple[-1]
4.5

my_tuple[1:4]

(2, 4, 1)

my_tuple[1:]

(2, 4, 1, 'apple', True, 4.5)

my_tuple[-2:]

(True, 4.5)

my_tuple[:3]

(1, 2, 4)

my_tuple[::2]

(1, 4, 'apple', 4.5)

my_tuple[::-1]

(4.5, True, 'apple', 1, 4, 2, 1)

t[2]

print(len(t))

t[2]=34

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[158], line 1
----> 1 t[2]=34

TypeError: 'tuple' object does not support item assignment

try:
t[0]=10
except TypeError as r:
print(r)

'tuple' object does not support item assignment

my_tuple = (1, 2, 3, "apple", 4.5)


for item in my_tuple:
print(item)

1
2
3
apple
4.5

for index, item in enumerate(my_tuple):


print(f"Index: {index}, Value: {item}")

Index: 0, Value: 1
Index: 1, Value: 2
Index: 2, Value: 3
Index: 3, Value: apple
Index: 4, Value: 4.5

"apple" in my_tuple

True

"banana" not in my_tuple

True

tuple1 = (1, 2, 3)
tuple2 = ("a", "b", "c")
tuple1 + tuple2

(1, 2, 3, 'a', 'b', 'c')

tuple1 * 2

(1, 2, 3, 1, 2, 3)

(0,) * 10

(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

packed_tuple=1,2,3,"apple"
print(packed_tuple,type(packed_tuple))

(1, 2, 3, 'apple') <class 'tuple'>

a,b,c,d=packed_tuple
print(a,b,c,d)

1 2 3 apple

a,b,*rest=packed_tuple
print(a,b,rest)
1 2 [3, 'apple']

my_tuple.index(3)

my_tuple.count(3)

my_dict = { "name": "Alice","age": 25,8:"New York",


("hobby_1","hobby_1"): ["reading", "hiking"]}
print(my_dict)

{'name': 'Alice', 'age': 25, 8: 'New York', ('hobby_1', 'hobby_1'):


['reading', 'hiking']}

my_dict = { "name": "Alice", "age": 25, 4:["a", "b"]}


my_dict["name"]

'Alice'

my_dict["Alice"]

----------------------------------------------------------------------
-----
KeyError Traceback (most recent call
last)
Cell In[48], line 1
----> 1 my_dict["Alice"]

KeyError: 'Alice'

my_dict.get("age")

25

my_dict.get("salary")

my_dict["salary"] = 50000
print(my_dict)

{'name': 'Alice', 'age': 25, 4: ['a', 'b'], 'salary': 50000}

my_dict["age"] = 26
print(my_dict)

{'name': 'Alice', 'age': 26, 4: ['a', 'b'], 'salary': 50000}

del my_dict["salary"]
print(my_dict)

{'name': 'Alice', 'age': 26, 4: ['a', 'b']}


my_dict.pop("age")
print(my_dict)

{'name': 'Alice', 4: ['a', 'b']}

my_dict = { "name": "Alex", "age": 25, "city": "AA"}

for key in my_dict:


print(key)

name
age
city

for value in my_dict.values():


print(value)

Alex
25
AA

for key, value in my_dict.items():


print(f"Key: {key}, Value: {value}")

Key: name, Value: Alex


Key: age, Value: 25
Key: city, Value: AA

my_dict.keys()

dict_keys(['name', 'age', 'city'])

my_dict.values()

dict_values(['Alex', 25, 'AA'])

my_dict.items()

dict_items([('name', 'Alex'), ('age', 25), ('city', 'AA')])

new_dict = my_dict.copy()
print(new_dict)

{'name': 'Alex', 'age': 25, 'city': 'AA'}

my_dict.clear()
print(my_dict)

{}

print(new_dict)

{'name': 'Alex', 'age': 25, 'city': 'AA'}


squares = {x: x**2 for x in range(1, 6)}
print(squares)

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

{x: x**2 for x in range(1, 6) if x % 2 == 0}

{2: 4, 4: 16}

my_set = {1, 2, 3, 3, 2, "apple"}


print(my_set)

{'apple', 2, 3, 1}

my_set = set([1, 2, 3, "apple", 4.5, True])


print(my_set)

{'apple', 1, 2, 3, 4.5}

my_set[0]

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[70], line 1
----> 1 my_set[0]

TypeError: 'set' object is not subscriptable

print(1 in my_set)

True

print("banana" in my_set)

False

set1 = {1, 2, 3}
set2 = {3, 4, 5}

set1 | set2

{1, 2, 3, 4, 5}

set1 & set2

{3}

set1 - set2

{1, 2}

set1 ^ set2
{1, 2, 4, 5}

for item in my_set:


print(item)

apple
1
2
3
4.5

my_set.add(4)
print(my_set)

{'apple', 1, 2, 3, 4.5, 4}

my_set.update([5, 6, "apple"])
print(my_set)

{'apple', 1, 2, 3, 4.5, 4, 5, 6}

my_set.copy()
print(my_set)

{'apple', 1, 2, 3, 4.5, 4, 5, 6}

my_set.remove("b")
print(my_set)

----------------------------------------------------------------------
-----
KeyError Traceback (most recent call
last)
Cell In[83], line 1
----> 1 my_set.remove("b")
2 print(my_set)

KeyError: 'b'

my_set.discard("b")
print(my_set)

{'apple', 1, 2, 3, 4.5, 4, 5, 6}

my_set.clear()
print(my_set)

set()

squares = {x**2 for x in range(-6, 6)}


print(squares)

{0, 1, 36, 4, 9, 16, 25}


even_squares = {x**2 for x in range(1, 6) if x % 2 == 0}
print(even_squares)

{16, 4}

path=r"C:\Users\tsion\OneDrive\Desktop\lab tes\[Link]"

file= open(path,'r')

type(file)

_io.TextIOWrapper

c=[Link]()
print(c)

fsdahgiyg
hdeyagreh,
chjjgydg\scbhsg
chjdgfg,s\

file = open("[Link]", "w")

file = open("[Link]", "a")

file = open("[Link]", "r+")

content = [Link]()
print(content)

[Link](0)
line = [Link]()
print(line)

[Link](0)
lines = [Link]()
print(lines)

[]

file = open("[Link]", "w")

[Link]("Hello, World!\n")

14

lines = ["This is the first line.\n","This is the second line.\n"]


[Link](lines)

[Link]()
file = open("[Link]", "a")
[Link]("This line will be added to the file.\n")
[Link]()

import os
cwd = [Link]()
print(cwd)

c:\Users\tsion\Downloads

full_path = [Link](cwd, "[Link]")


print(full_path)

c:\Users\tsion\Downloads\[Link]

print([Link](full_path))

True

with open("[Link]", "r") as file:


content = [Link]()
print(content)

Hello, World!
This is the first line.
This is the second line.
This line will be added to the file.

import pickle
data = {'name': 'Alice', 'age': 25, 'city': 'New York'}

with open('[Link]', 'wb') as file:


[Link](data, file)

with open('[Link]', 'rb') as file:


loaded_data = [Link](file)
print(loaded_data)

{'name': 'Alice', 'age': 25, 'city': 'New York'}

try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Division successful")
finally:
print("Execution completed")

Cannot divide by zero


Execution completed
try:
with open('non_existent_file.txt', 'r') as file:
content = [Link]()
except FileNotFoundError:
print("File not found. Please check the file name and path.")
except IOError:
print("An error occurred while reading the file.")
else:
print("File read successfully")

File not found. Please check the file name and path.

class Dog:
def __init__(self, name, age):
[Link] = name
[Link] = age
def bark(self):
return f"{[Link]} says woof!"

dog1 = Dog("Buddy", 3)
dog2 = Dog("Lucy", 5)

print([Link])

Buddy

print([Link])

[Link]()

'Buddy says woof!'

[Link]()

'Lucy says woof!'

[Link] = 4
print([Link])

[Link] = "Labrador"
print([Link])

Labrador

class Animal:
def speak(self):
print("Animal speaks")

class Dog(Animal):
def bark(self):
print("Dog barks")

dog = Dog()

[Link]()

Animal speaks

[Link]()

Dog barks

class Cat(Animal):
def speak(self):
print("Cat meows")

cat = Cat()

[Link]()

Cat meows

You might also like