0% found this document useful (0 votes)
6 views25 pages

Python Practical

The document provides an overview of various programming concepts including flow control, functions, string manipulation, operations on tuples, lists, sets, dictionaries, object-oriented programming, method overloading, file handling, regular expressions, modules, packages, and exception handling. Each section includes code examples and their corresponding outputs to illustrate the concepts. It serves as a comprehensive guide for basic programming techniques and practices.

Uploaded by

Loner
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)
6 views25 pages

Python Practical

The document provides an overview of various programming concepts including flow control, functions, string manipulation, operations on tuples, lists, sets, dictionaries, object-oriented programming, method overloading, file handling, regular expressions, modules, packages, and exception handling. Each section includes code examples and their corresponding outputs to illustrate the concepts. It serves as a comprehensive guide for basic programming techniques and practices.

Uploaded by

Loner
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

1.

FLOW CONTROL , FUNCTIONS AND STRING MANIPULATION

IF ,ELIF,ELSE STATEMENT

age = 20

if age >= 18:

print("You are an adult.")

elif age >= 13:

print("You are a teenager.")

else:

print("You are a child.")

FOR LOOP STATEMENT

for i in range(5):

print(i)

WHILE LOOP STATEMENT

count = 0

while count < 3:

print(count)

count += 1

BREAK,CONTINUE STATEMENT

numbers=[1,2,3,4,5,6,7,8,9,10]

for num in numbers:

if num == 5:

break

if num%2==0:

continue

print(num)
NESTED LOOP STATEMENT

for i in range(3):

for j in range(2):

print(i,j)

FUNCTIONS

def add_numbers(num1, num2):

sum = num1 + num2

print("Sum: ", sum)

add_numbers(5, 4)

STRING MANIPULATION

original_string = "Hello, World!"

print("Uppercase:", original_string.upper())

print("Lowercase:", original_string.lower())

string_with_whitespace = " Hello, World! "

print("Strip whitespace:", string_with_whitespace.strip())

string_to_split = "apple,banana,cherry"

print("Split string:", string_to_split.split(","))

fruits = ["apple", "banana", "cherry"]

print("Join strings:", ",".join(fruits))

string_to_replace = "Hello, World!"

print("Replace string:", string_to_replace.replace("World", "Universe"))

print("Find index:", original_string.find("World"))

print("Index:", original_string.index("World"))

string1 = "Hello"

string2 = "World"
print("Concatenation:", string1 + ", " + string2 + "!")

print("Slicing:", original_string[0:5])

name = "John"

age = 30

print("f-string:", f"My name is {name} and I am {age} years old.")

print("format():", "My name is {} and I am {} years old.".format(name, age))


OUTPUT

IF,ELIF,ELSE STATEMENT

You are an adult.

FOR LOOP STATEMENT

WHILE LOOP STATEMENT

BREAK,CONTINUE STATEMENT

NESTED LOOP STATEMENT

00

01

10

11

20

21

FUNCTIONS OUTPUT

Sum: 9

STRING MANIPULATION

Uppercase: HELLO, WORLD!


Lowercase: hello, world!

Strip whitespace: Hello, World!

Split string: ['apple', 'banana', 'cherry']

Join strings: apple,banana,cherry

Replace string: Hello, Universe!

Find index: 7

Index: 7

Concatenation: Hello, World!

Slicing: Hello

f-string: My name is John and I am 30 years old.

format(): My name is John and I am 30 years old.


2. OPERATIONS ON TUPLES AND LISTS

TUPLE OPERATIONS

my_tuple = (1, 2, 3, 4, 5)

print(my_tuple[0])

print(my_tuple[1:3])

print(len(my_tuple))

LIST OPERATIONS

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

my_list.append(6)

print(my_list)

my_list.insert(0, 0)

print(my_list)

my_list.remove(2)

print(my_list)

my_list.sort(reverse=True)

print(my_list)
OUTPUT

TUPLE OPERATIONS

(2, 3)

LIST OPERATIONS

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

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

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

[6, 5, 4, 3, 1, 0]
3. OPERATIONS ON SETS

A = {1, 2, 3, 4, 5}

B = {4, 5, 6, 7, 8}

print([Link](B))

print(A | B)

print([Link](B))

print(A & B)

print([Link](B))

print(A - B)

print(A.symmetric_difference(B))

print(A ^ B)

[Link](9)

print(A)

[Link](5)

print(A)

[Link](4)

print(A)

[Link]()

print(A)
OUTPUT

{1, 2, 3, 4, 5, 6, 7, 8}

{1, 2, 3, 4, 5, 6, 7, 8}

{4, 5}

{4, 5}

{1, 2, 3}

{1, 2, 3}

{1, 2, 3, 6, 7, 8}

{1, 2, 3, 6, 7, 8}

{1, 2, 3, 4, 5, 9}

{1, 2, 3, 4, 9}

{1, 2, 3, 9}

set()
[Link] ON DICTIONARY

person = {"name": "John", "age": 30, "city": "New York"}

print("Accessing values:")

print(person["name"])

print([Link]("age"))

person["country"] = "USA"

person["age"] = 31

print("\n After adding/updating values:")

print(person)

del person["city"]

print("\n After removing 'city' key:")

print(person)

[Link]("age")

print("\n After removing 'age' key:")

print(person)

print("\n Checking if a key exists:")

print("name" in person)

print("age" in person)

print("\n Dictionary methods:")

print([Link]())

print([Link]())

print([Link]())

[Link]({"age": 32, "city": "Los Angeles"})

print("\n After updating dictionary:")

print(person)

[Link]()

print(person)
OUTPUT

Accessing values:

John

30

After adding/updating values:

{'name': 'John', 'age': 31, 'city': 'New York', 'country': 'USA'}

After removing 'city' key:

{'name': 'John', 'age': 31, 'country': 'USA'}

After removing 'age' key:

{'name': 'John', 'country': 'USA'}

Checking if a key exists:

True

False

Dictionary methods:

dict_keys(['name', 'country'])

dict_values(['John', 'USA'])

dict_items([('name', 'John'), ('country', 'USA')])

After updating dictionary:

{'name': 'John', 'country': 'USA', 'age': 32, 'city': 'Los Angeles'}

{}
[Link] OOP– CONSTRUCTORS – CREATE A CLASS FOR REPRESENTING A
CAR

class Car:

def __init__(self, brand, model):

[Link] = brand

[Link] = model

def show(self):

print("Car Brand:", [Link])

print("Car Model:", [Link])

my_car = Car("Honda", "Civic")

my_car.show()
OUTPUT

Car Brand: Honda

Car Model: Civic


[Link] OVERLOADING – CREATE CLASSES FOR VEHICLE AND BUS AND
DEMONSTRATE METHOD OVERLOADING.

class Vehicle:

def show(self, name="Vehicle"):

print("Vehicle Name:", name)

class Bus(Vehicle):

def show(self, name="Bus", capacity=None):

if capacity:

print(f"Bus Name: {name}, Capacity: {capacity} seats")

else:

print(f"Bus Name: {name}")

v = Vehicle()

b = Bus()

[Link]()

[Link]("Bike")

[Link]()

[Link]("City Bus", 40)


OUTPUT:

Vehicle Name: Vehicle

Vehicle Name: Bike

Bus Name: Bus

Bus Name: City Bus, Capacity: 40 seats


[Link] – READING AND WRITING – PERFORM THE BASIC OPERATION OF
READING AND WRITING WITH STUDENT FILE

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

[Link]("Name: John\n")

[Link]("Roll No: 101\n")

[Link]("Department: Computer Science\n")

[Link]()

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

print("Student File Content:\n")

print([Link]())

[Link]()
OUTPUT:

Student File Content:

Name: John

Roll No: 101

Department: Computer Science


[Link] EXPRESSIONS

import re

text = "My email is example123@[Link] and my phone number is 9876543210."

email_pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"

phone_pattern = r"\b\d{10}\b"

email = [Link](email_pattern, text)

if email:

print("Email found:", [Link]())

phone = [Link](phone_pattern, text)

if phone:

print("Phone number found:", [Link]())


OUTPUT:

Email found: example123@[Link]

Phone number found: 9876543210


9. Modules

1. Create a module file (e.g., [Link])

def greet(name):

return f"Hello, {name}!"

def add(a, b):

return a + b

Main program file (e.g., [Link])

import mymodule # importing our custom module

print([Link]("Alice"))

print("Sum:", [Link](5, 7))

2. Create the Module (Save as math_module.py)

def square(x):

return x * x

def cube(x):

return x * x * x

Main Program (Save as [Link])

import math_module

print("Square of 3:", math_module.square(3))

print("Cube of 2:", math_module.cube(2))


OUTPUT 1:

Hello, Alice!

Sum: 12

OUTPUT 2:

Square of 3: 9

Cube of 2: 8
10. Packages

Folder Structure:

my_package/

├── __init__.py

├── math_ops.py

└── string_ops.py

[Link]

my_package/math_ops.py

def add(a, b):

return a + b

def subtract(a, b):

return a - b

my_package/string_ops.py

def to_upper(s):

return [Link]()

def reverse(s):

return s[::-1]

[Link] (Main Program)

from my_package import math_ops, string_ops

print("Addition:", math_ops.add(5, 3))

print("Subtraction:", math_ops.subtract(10, 4))

print("Uppercase:", string_ops.to_upper("hello"))

print("Reversed:", string_ops.reverse("world"))
OUTPUT:

Addition: 8

Subtraction: 6

Uppercase: HELLO

Reversed: dlrow
[Link] Handling

try:

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

num2 = int(input("Enter another number: "))

result = num1 / num2

print("Result:", result)

except ZeroDivisionError:

print("Error: Cannot divide by zero.")

except ValueError:

print("Error: Please enter valid integers.")

finally:

print("Program ended.")
OUTPUT:

Enter a number: 10

Enter another number: 0

Error: Cannot divide by zero.

Program ended.

Enter a number: ten

Enter another number: 2

Error: Please enter valid integers.

Program ended.

You might also like