0% found this document useful (0 votes)
3 views

python-practicals (7)

The document outlines practical programming exercises in Python, focusing on the math module, string manipulation, and dictionary modifications. It includes code examples demonstrating basic math functions, trigonometric calculations, string operations, and various methods for modifying dictionary values. Each section provides outputs to illustrate the results of the operations performed.
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)
3 views

python-practicals (7)

The document outlines practical programming exercises in Python, focusing on the math module, string manipulation, and dictionary modifications. It includes code examples demonstrating basic math functions, trigonometric calculations, string operations, and various methods for modifying dictionary values. Each section provides outputs to illustrate the results of the operations performed.
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/ 7

Practical 20: Math Module Program

Practical Name: Math Module Program Objective: To demonstrate the


usage of Python’s math module and mathematical operations.
import math

def demonstrate_math_module():
# Basic math functions
print("Basic Math Functions:")
numbers = [4, 9, 16, 25]
for num in numbers:
print(f"Square root of {num}: {math.sqrt(num)}")

# Trigonometric functions
angles = [0, 30, 45, 60, 90]
print("\nTrigonometric Functions (angles in degrees):")
for angle in angles:
# Convert to radians for trig functions
rad = math.radians(angle)
print(f"Angle: {angle}°")
print(f"Sin: {math.sin(rad):.4f}")
print(f"Cos: {math.cos(rad):.4f}")
print(f"Tan: {math.tan(rad):.4f if angle != 90 else 'undefined'}")

# Constants and special values


print("\nMath Constants:")
print(f"� (pi): {math.pi:.6f}")
print(f"e: {math.e:.6f}")
print(f"tau (2�): {math.tau:.6f}")

# Floor, ceiling, and rounding


numbers = [3.1, 3.5, 3.9, -3.1, -3.5, -3.9]
print("\nRounding Functions:")
for num in numbers:
print(f"Number: {num}")
print(f"Floor: {math.floor(num)}")
print(f"Ceil: {math.ceil(num)}")
print(f"Round: {round(num)}")
print()

demonstrate_math_module()
Output:
Basic Math Functions:
Square root of 4: 2.0

1
Square root of 9: 3.0
Square root of 16: 4.0
Square root of 25: 5.0

Trigonometric Functions (angles in degrees):


Angle: 0°
Sin: 0.0000
Cos: 1.0000
Tan: 0.0000
Angle: 30°
Sin: 0.5000
Cos: 0.8660
Tan: 0.5774
Angle: 45°
Sin: 0.7071
Cos: 0.7071
Tan: 1.0000
Angle: 60°
Sin: 0.8660
Cos: 0.5000
Tan: 1.7321
Angle: 90°
Sin: 1.0000
Cos: 0.0000
Tan: undefined

Math Constants:
� (pi): 3.141593
e: 2.718282
tau (2�): 6.283185

Rounding Functions:
Number: 3.1
Floor: 3
Ceil: 4
Round: 3

Number: 3.5
Floor: 3
Ceil: 4
Round: 4

Number: 3.9
Floor: 3
Ceil: 4
Round: 4

2
Number: -3.1
Floor: -4
Ceil: -3
Round: -3

Number: -3.5
Floor: -4
Ceil: -3
Round: -4

Number: -3.9
Floor: -4
Ceil: -3
Round: -4

Practical 21: String Program


Practical Name: String Program Objective: To demonstrate string manipu-
lation and various string operations in Python.
def demonstrate_string_operations():
# String creation and basic operations
text = "Python Programming"
print("Original string:", text)
print("Length:", len(text))
print("Uppercase:", text.upper())
print("Lowercase:", text.lower())

# String slicing
print("\nString Slicing:")
print("First 6 characters:", text[:6])
print("Last 11 characters:", text[-11:])
print("Every second character:", text[::2])
print("Reversed string:", text[::-1])

# String methods
print("\nString Methods:")
sentence = " Python is a great programming language "
print("Original:", sentence)
print("Stripped:", sentence.strip())
print("Split words:", sentence.split())
print("Replace 'great' with 'awesome':", sentence.replace('great', 'awesome'))

# String formatting
print("\nString Formatting:")

3
name = "Alice"
age = 25
height = 1.75

# Using format() method


print("Using format(): {} is {} years old and {} meters tall".format(name, age, height))

# Using f-strings
print(f"Using f-string: {name} is {age} years old and {height:.2f} meters tall")

# String checking methods


print("\nString Checking:")
texts = ["Python123", "123", "PYTHON", "python", " ", ""]
for t in texts:
print(f"\nChecking string: '{t}'")
print(f"Is alphanumeric? {t.isalnum()}")
print(f"Is alphabetic? {t.isalpha()}")
print(f"Is numeric? {t.isnumeric()}")
print(f"Is uppercase? {t.isupper()}")
print(f"Is lowercase? {t.islower()}")
print(f"Is space? {t.isspace()}")

demonstrate_string_operations()
Output:
Original string: Python Programming
Length: 18
Uppercase: PYTHON PROGRAMMING
Lowercase: python programming

String Slicing:
First 6 characters: Python
Last 11 characters: Programming
Every second character: PtoPormig
Reversed string: gnimmargorP nohtyP

String Methods:
Original: Python is a great programming language
Stripped: Python is a great programming language
Split words: ['Python', 'is', 'a', 'great', 'programming', 'language']
Replace 'great' with 'awesome': Python is a awesome programming language

String Formatting:
Using format(): Alice is 25 years old and 1.75 meters tall
Using f-string: Alice is 25 years old and 1.75 meters tall

4
String Checking:
Checking string: 'Python123'
Is alphanumeric? True
Is alphabetic? False
Is numeric? False
Is uppercase? False
Is lowercase? False
Is space? False

Checking string: '123'


Is alphanumeric? True
Is alphabetic? False
Is numeric? True
Is uppercase? False
Is lowercase? False
Is space? False

Checking string: 'PYTHON'


Is alphanumeric? True
Is alphabetic? True
Is numeric? False
Is uppercase? True
Is lowercase? False
Is space? False

[Output truncated for brevity...]

Practical 22: Change Dictionary Value Program


Practical Name: Change Dictionary Value Program Objective: To demon-
strate various methods of modifying dictionary values in Python.
def demonstrate_dictionary_modifications():
# Create initial dictionary
student = {
'name': 'John Doe',
'age': 20,
'grades': {
'math': 85,
'science': 90,
'history': 88
},
'courses': ['Math', 'Science', 'History']
}

print("Original dictionary:", student)

5
# Method 1: Direct assignment
student['age'] = 21
print("\nAfter changing age directly:", student)

# Method 2: Using update() method


student.update({'name': 'John Smith', 'age': 22})
print("\nAfter using update():", student)

# Method 3: Modifying nested dictionary


student['grades']['math'] = 95
print("\nAfter changing math grade:", student)

# Method 4: Using setdefault()


student.setdefault('email', '[email protected]')
print("\nAfter using setdefault():", student)

# Method 5: Dictionary comprehension


student['grades'] = {subject: score + 5 for subject, score in student['grades'].items()}
print("\nAfter updating all grades:", student)

# Method 6: Modifying list within dictionary


student['courses'].append('English')
print("\nAfter adding new course:", student)

# Method 7: Conditional modification


for subject in student['grades']:
if student['grades'][subject] > 90:
student['grades'][subject] = 'A'
else:
student['grades'][subject] = 'B'

print("\nAfter converting grades to letters:", student)

demonstrate_dictionary_modifications()
Output:
Original dictionary: {'name': 'John Doe', 'age': 20, 'grades': {'math': 85, 'science': 90, '

After changing age directly: {'name': 'John Doe', 'age': 21, 'grades': {'math': 85, 'science

After using update(): {'name': 'John Smith', 'age': 22, 'grades': {'math': 85, 'science': 90

After changing math grade: {'name': 'John Smith', 'age': 22, 'grades': {'math': 95, 'science

After using setdefault(): {'name': 'John Smith', 'age': 22, 'grades': {'math': 95, 'science'

6
After updating all grades: {'name': 'John Smith', 'age': 22, 'grades': {'math': 100, 'scienc

After adding new course: {'name': 'John Smith', 'age': 22, 'grades': {'math': 100, 'science'

After converting grades to letters: {'name': 'John Smith', 'age': 22, 'grades': {'math': 'A'
Would you like me to continue with the next set of practicals? We can cover
file operations, error handling, and some advanced Python concepts next.

You might also like