0% found this document useful (0 votes)
5 views4 pages

Python Programs

The document provides an overview of various functions and methods in Python, including operations on lists, tuples, dictionaries, and user-defined functions. It also covers classes and objects, basic NumPy array manipulations, data manipulation with Pandas, and visualization techniques using Matplotlib. Each section includes code examples demonstrating the functionality of these features.

Uploaded by

amanverma282003
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)
5 views4 pages

Python Programs

The document provides an overview of various functions and methods in Python, including operations on lists, tuples, dictionaries, and user-defined functions. It also covers classes and objects, basic NumPy array manipulations, data manipulation with Pandas, and visualization techniques using Matplotlib. Each section includes code examples demonstrating the functionality of these features.

Uploaded by

amanverma282003
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

List Functions/Methods in Python

my_list = list([1, 2, 3, 4])


print("1. list() ->", my_list)
print("2. len(my_list) ->", len(my_list))
print("3. count(2) ->", my_list.count(2))
print("4. index(3) ->", my_list.index(3))
my_list.append(5)
print("5. append(5) ->", my_list)
my_list.insert(2, 10)
print("6. insert(2, 10) ->", my_list)
my_list.extend([6, 7, 8])
print("7. extend([6, 7, 8]) ->", my_list)
my_list.remove(10)
print("8. remove(10) ->", my_list)
popped = my_list.pop()
print("9. pop() ->", popped, "Remaining:", my_list)
my_list.reverse()
print("10. reverse() ->", my_list)
numbers = [4, 2, 9, 1, 7]
numbers.sort()
print("11. sort() ->", numbers)
copy_list = numbers.copy()
print("12. copy() ->", copy_list)
numbers.clear()
print("13. clear() ->", numbers)

Tuple Functions/Methods in Python

my_tuple = (10, 20, 30, 20, 40, 50)


print("1. len(my_tuple) ->", len(my_tuple))
print("2. count(20) ->", my_tuple.count(20))
print("3. index(30) ->", my_tuple.index(30))
print("4. sorted(my_tuple) ->", sorted(my_tuple))
print("5. min(my_tuple) ->", min(my_tuple))
print("6. max(my_tuple) ->", max(my_tuple))
t1 = (1, 2, 3)
t2 = (1, 3, 2)
print("7. cmp() replacement ->")
print(" t1 == t2 ?", t1 == t2)
print(" t1 < t2 ?", t1 < t2)
print(" t1 > t2 ?", t1 > t2)
print("8. reversed(my_tuple) ->", tuple(reversed(my_tuple)))
Dictionary Functions/Methods in Python

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


print("Dictionary:", my_dict)
print("Length:", len(my_dict))
print("Get age:", my_dict.get("age"))
my_dict["country"] = "USA"
print("After update:", my_dict)
my_dict.pop("city")
print("After pop('city'):", my_dict)
my_dict.popitem()
print("After popitem():", my_dict)
print("Keys:", my_dict.keys())
print("Values:", my_dict.values())
print("Items:", my_dict.items())
copy_dict = my_dict.copy()
print("Copy:", copy_dict)
copy_dict.clear()
print("After clear():", copy_dict)

Functions in Python

print("1. Built-in Function: len() ->", len([1, 2, 3, 4])) # Counts number of elements
def greet(name):
return f"Hello, {name}!"
print("2. User-defined Function ->", greet("Alice"))
square = lambda x: x**2
print("3. Lambda Function -> square(5) =", square(5))
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
print("4. Recursion Function -> factorial(5) =", factorial(5))

Classes and Objects

class Student:
def __init__(self, name, age, roll_no):
self.name = name
self.age = age
self.roll_no = roll_no
def display(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
print(f"Roll No: {self.roll_no}")
student1 = Student("Alice", 20, 101)
student2 = Student("Bob", 22, 102)
print("Student 1 Details:")
student1.display()
print("\nStudent 2 Details:")
student2.display()

Basics of NumPy Arrays

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print("Array:", arr)
print("Array + 5:", arr + 5)
print("Array * 2:", arr * 2)
print("First element:", arr[0])
print("Last two elements:", arr[-2:])
print("Elements greater than 3:", arr[arr > 3])

Data Manipulation with Pandas

import pandas as pd
data = {
"StudentID": [1, 2, 3, 4],
"Name": ["Alice", "Bob", "Charlie", "David"],
"Age": [20, 21, 19, 22],
"Grade": ["A", "B", "A", "C"]
}
df = pd.DataFrame(data)
print("1. DataFrame:\n", df, "\n")
print("2. First 2 rows:\n", df.head(2), "\n")
print("3. Names Column:\n", df["Name"], "\n")
print("4. Students with Age > 20:\n", df[df["Age"] > 20], "\n")
df["Passed"] = df["Grade"].apply(lambda x: True if x in ["A", "B"] else False)
print("5. After adding 'Passed' column:\n", df, "\n")
df.drop("Passed", axis=1, inplace=True)
print("6. After deleting 'Passed' column:\n", df, "\n")
print("7. Statistics on Age:")
print(" Mean Age:", df["Age"].mean())
print(" Max Age:", df["Age"].max())
print(" Min Age:", df["Age"].min())
Visualization with Matplotlib

import matplotlib.pyplot as plt


x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
y2 = [1, 3, 5, 7, 9]
plt.figure(figsize=(8,4))
plt.plot(x, y, color='blue', marker='o', linestyle='-', label='y = 2x')
plt.plot(x, y2, color='red', marker='s', linestyle='--', label='y = 2x - 1')
plt.title("Line Plot Example")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
plt.grid(True)
plt.show()
plt.figure(figsize=(8,4))
plt.scatter(x, y, color='green', label='y = 2x', s=100) # s=size of markers
plt.scatter(x, y2, color='orange', label='y = 2x - 1', s=100)
plt.title("Scatter Plot Example")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
plt.grid(True)
plt.show()

You might also like