0% found this document useful (0 votes)
4 views11 pages

PYTHON PROGRAMS

The document contains a collection of Python programs demonstrating various programming concepts such as calculations, data structures (lists, tuples, sets, dictionaries), inheritance, and control flow. Each program includes code snippets with examples for practical understanding. Topics covered range from basic arithmetic operations to object-oriented programming and data manipulation.

Uploaded by

radhikagawali102
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views11 pages

PYTHON PROGRAMS

The document contains a collection of Python programs demonstrating various programming concepts such as calculations, data structures (lists, tuples, sets, dictionaries), inheritance, and control flow. Each program includes code snippets with examples for practical understanding. Topics covered range from basic arithmetic operations to object-oriented programming and data manipulation.

Uploaded by

radhikagawali102
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

PYTHON PROGRAMS

1. Calculate surface volume and area of a cylinder


```python
import math

def cylinder_calculations(radius, height):


volume = math.pi * radius**2 * height
surface_area = 2 * math.pi * radius * (radius + height)
return volume, surface_area

# Example usage
radius = 5
height = 10
vol, area = cylinder_calculations(radius, height)
print(f"Volume: {vol:.2f}, Surface Area: {area:.2f}")
```

2. Import module for addition and subtraction


```python
# Save this as math_operations.py
def add(a, b):
return a + b

def subtract(a, b):


return a - b

# In another file:
# from math_operations import add, subtract
# print(add(5, 3)) # Output: 8
# print(subtract(5, 3)) # Output: 2
```

3. List operations
```python
# Create a List
my_list = [1, 2, 3, 'apple', 'banana']
# Access List
print(my_list[0]) # First element
print(my_list[-1]) # Last element

# Update List
my_list[1] = 'orange'
my_list.append(42)

# Delete List
del my_list[2] # Remove specific item
my_list.remove('apple') # Remove by value
# del my_list # To delete entire list
```

4. Tuple operations
```python
# Create a Tuple
my_tuple = (1, 2, 3, 'a', 'b')

# Access Tuple
print(my_tuple[0]) # First element
print(my_tuple[-1]) # Last element

# Print Tuple
print(my_tuple)

# Delete Tuple
# del my_tuple # Uncomment to delete

# Convert between tuple and list


tuple_to_list = list(my_tuple)
list_to_tuple = tuple([4, 5, 6])
```

5. Set operations
```python
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Union
print(set1.union(set2)) # or set1 | set2

# Intersection
print(set1.intersection(set2)) # or set1 & set2

# Difference
print(set1.difference(set2)) # or set1 - set2

# Symmetric Difference
print(set1.symmetric_difference(set2)) # or set1 ^ set2
```

6. Dictionary operations
```python
# Create a Dictionary
student = {'name': 'John', 'age': 20, 'grade': 'A'}

# Access Dictionary
print(student['name'])
print(student.get('age'))

# Update Dictionary
student['age'] = 21
student.update({'grade': 'B', 'city': 'New York'})

# Delete Dictionary
del student['city']
# del student # To delete entire dictionary

# Looping through Dictionary


for key, value in student.items():
print(f"{key}: {value}")

# Create Dictionary from list


keys = ['a', 'b', 'c']
values = [1, 2, 3]
new_dict = dict(zip(keys, values))
```

7. User defined package


```python
# Create a folder named 'mypackage' with __init__.py and math_ops.py
# math_ops.py content:
def add(a, b):
return a + b

def multiply(a, b):


return a * b

# Then use it:


# from mypackage.math_ops import add, multiply
# print(add(2, 3))
```

8. Student class
```python
class Student:
def __init__(self, name, age, roll_number, marks):
self.name = name
self.age = age
self.roll_number = roll_number
self.marks = marks

# Create instances
student1 = Student("Alice", 20, "S001", 85)
student2 = Student("Bob", 21, "S002", 78)

# Print attributes
print(f"Student 1: {student1.name}, {student1.age}, {student1.roll_number}, {student1.marks}")
print(f"Student 2: {student2.name}, {student2.age}, {student2.roll_number}, {student2.marks}")
```

9. Single inheritance
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

class Student(Person):
def __init__(self, name, age, roll_number, marks):
super().__init__(name, age)
self.roll_number = roll_number
self.marks = marks

# Create instance
student = Student("Charlie", 19, "S003", 92)
print(f"{student.name}, {student.age}, {student.roll_number}, {student.marks}")
```

10. Multiple inheritance


```python
class Sports:
def __init__(self, sports_name):
self.sports_name = sports_name

def display_sports(self):
print(f"Sport: {self.sports_name}")

class Academic:
def __init__(self, grade):
self.grade = grade

def display_grade(self):
print(f"Grade: {self.grade}")

class Student(Sports, Academic):


def __init__(self, name, age, sports_name, grade):
Sports.__init__(self, sports_name)
Academic.__init__(self, grade)
self.name = name
self.age = age

def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
self.display_sports()
self.display_grade()

# Create instance
student = Student("David", 20, "Basketball", "A")
student.display_info()
```
11. Multilevel inheritance
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

class Student(Person):
def __init__(self, name, age, roll_number, marks):
super().__init__(name, age)
self.roll_number = roll_number
self.marks = marks

class GraduateStudent(Student):
def __init__(self, name, age, roll_number, marks, thesis_topic):
super().__init__(name, age, roll_number, marks)
self.thesis_topic = thesis_topic

# Create instance
grad_student = GraduateStudent("Eve", 25, "G001", 88, "Machine Learning")
print(f"{grad_student.name}, {grad_student.age}, {grad_student.roll_number},
{grad_student.marks}, {grad_student.thesis_topic}")
```

12. Highest 3 values in dictionary


```python
def top_three_items(d):
sorted_items = sorted(d.items(), key=lambda x: x[1], reverse=True)
return sorted_items[:3]

my_dict = {'a': 100, 'b': 400, 'c': 300, 'd': 200}


print(top_three_items(my_dict))
```

13. Set operations (same as question 5)


```python
# Same as question 5
```

14. Fibonacci series


```python
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b

fibonacci(10) # Print first 10 Fibonacci numbers


```

15. Largest among three numbers


```python
def find_largest(a, b, c):
return max(a, b, c)

# Example
print(find_largest(10, 20, 5)) # Output: 20
```

16. Leap year check


```python
def is_leap_year(year):
if year % 4 != 0:
return False
elif year % 100 != 0:
return True
else:
return year % 400 == 0

# Example
print(is_leap_year(2020)) # True
print(is_leap_year(1900)) # False
```
17. Positive, negative or zero
```python
def check_number(num):
if num > 0:
return "Positive"
elif num < 0:
return "Negative"
else:
return "Zero"

# Example
print(check_number(5)) # Positive
print(check_number(-3)) # Negative
print(check_number(0)) # Zero
```

18. Grade calculator


```python
def calculate_grade(scores):
average = sum(scores) / len(scores)
if average >= 90:
return 'A'
elif average >= 80:
return 'B'
elif average >= 70:
return 'C'
elif average >= 60:
return 'D'
else:
return 'F'

# Example
marks = [85, 90, 78, 92, 88]
print(f"Grade: {calculate_grade(marks)}")
```

19. Palindrome check


```python
def is_palindrome(num):
return str(num) == str(num)[::-1]

# Example
print(is_palindrome(121)) # True
print(is_palindrome(123)) # False
```

20. Even numbers with while loop


```python
num = 1
while num <= 100:
if num % 2 == 0:
print(num, end=' ')
num += 1
```

21. Break statement


```python
for i in range(10):
if i == 5:
break
print(i, end=' ')
# Output: 0 1 2 3 4
```

22. Common items in two lists


```python
def common_items(list1, list2):
return list(set(list1) & set(list2))

# Example
list_a = [1, 2, 3, 4, 5]
list_b = [4, 5, 6, 7, 8]
print(common_items(list_a, list_b)) # [4, 5]
```
23. Max and min from set
```python
my_set = {5, 2, 8, 1, 9}
print(f"Max: {max(my_set)}, Min: {min(my_set)}")
```

24. Prime number check


```python
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True

# Example
print(is_prime(7)) # True
print(is_prime(10)) # False
```

25. Factorial calculation


```python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

# Example
print(factorial(5)) # 120
```

26. Count upper and lower case letters


```python
def count_case_letters(s):
upper = sum(1 for c in s if c.isupper())
lower = sum(1 for c in s if c.islower())
return upper, lower

# Example
text = "Hello World"
upper, lower = count_case_letters(text)
print(f"Uppercase: {upper}, Lowercase: {lower}")
```

27. Student information with inheritance (5 students)


```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

class Student(Person):
def __init__(self, name, age, roll_number, marks):
super().__init__(name, age)
self.roll_number = roll_number
self.marks = marks

def display_info(self):
print(f"Name: {self.name}, Age: {self.age}, Roll: {self.roll_number}, Marks: {self.marks}")

# Create 5 students
students = [
Student("Alice", 20, "S001", 85),
Student("Bob", 21, "S002", 78),
Student("Charlie", 19, "S003", 92),
Student("Diana", 22, "S004", 88),
Student("Eve", 20, "S005", 95)
]

# Display all students


for student in students:
student.display_info()
```

You might also like