Pythonexameple Code for Builtins Fumctipns
Pythonexameple Code for Builtins Fumctipns
Here are some example codes for common Python built-in functions:
Page 1 of 12
PYTHON EXAMPLE CODE FOR ITETATORS
print(next(iterator)) # Output: 10
print(next(iterator)) # Output: 20
print(next(iterator)) # Output: 30
print(next(iterator)) # Output: 40
# print(next(iterator)) # Raises StopIteration error if uncommented
def __iter__(self):
return self # An iterator must return itself
def __next__(self):
if self.current >= self.end:
raise StopIteration # Stop iteration when limit is reached
self.current += 1
return self.current - 1 # Return current value before incrementing
counter = Counter(1, 5)
for num in counter:
print(num)
# Output:
# 1
# 2
# 3
# 4
def random_number():
return random.randint(1, 10)
Page 2 of 12
PYTHON EXAMPLES CODE FOR MATPLOTLIB
matplotlib is a popular Python library for creating visualizations. Below are some basic examples of how to use it:
1. Install Matplotlib
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
3. Bar Chart
categories = ["A", "B", "C", "D"]
values = [10, 20, 15, 25]
4. Scatter Plot
import numpy as np
x = np.random.rand(50)
y = np.random.rand(50)
5. Histogram
data = np.random.randn(1000) # Generate random data
6. Pie Chart
labels = ["Python", "Java", "C++", "JavaScript"]
sizes = [40, 30, 15, 15]
colors = ["blue", "red", "green", "purple"]
Page 3 of 12
PYTHON EXAMPLE CODE FOR SCIKIT-LEARN
Scikit-learn is a powerful machine learning library in Python. It provides tools for classification, regression, clustering, and more.
1. Install Scikit-Learn
If you haven’t installed it yet, run:
Pip install scikit-learn
Basic Examples
1. Importing scikit-learn
Import numpy as np
Import pandas as pd
From sklearn.model_selection import train_test_split
From sklearn.preprocessing import StandardScaler
From sklearn.linear_model import LogisticRegression
From sklearn.metrics import accuracy_score
Iris = datasets.load_iris()
X = iris.data
Y = iris.target
.Standardizing Data
Page 4 of 12
Scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
Model = LogisticRegression()
Model.fit(X_train, y_train)
Y_pred = model.predict(X_test)
Y_pred_rf = rf_model.predict(X_test)
# Sample dataset
X_reg = np.array([[1], [2], [3], [4], [5]])
Y_reg = np.array([2, 4, 6, 8, 10])
Reg_model = LinearRegression()
Reg_model.fit(X_reg, y_reg)
Y_pred_reg = reg_model.predict([[6]])
Print(“Predicted Value for 6:”, y_pred_reg[0])
Page 6 of 12
PYTHON EXAMPLE CODE FOR POLYMARPHISM
Polymorphism in Python
Polymorphism allows different classes to have methods with the same name but different behaviors. This makes code more flexible and reusable.
Different classes can have the same method name, but their implementation differs.
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
# Using polymorphism
animals = [Dog(), Cat()]
# Output:
# Woof!
# Meow!
class Animal:
def make_sound(self):
return "Some sound"
class Dog(Animal):
def make_sound(self):
return "Bark"
class Cat(Animal):
def make_sound(self):
return "Meow"
# Using polymorphism
animals = [Dog(), Cat(), Animal()]
# Output:
# Bark
# Meow
# Some sound
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Square(Shape):
Page 7 of 12
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
# Output:
# 78.5 (Area of Circle)
# 16 (Area of Square)
Page 8 of 12
PYTHONEXAMEPLE CODE FOR CLASS
Python Class Examples
A class in Python is a blueprint for creating objects. It defines properties (attributes) and behaviors (methods).
Class Person:
Def __init__(self, name, age): # Constructor
Self.name = name
Self.age = age
# Creating an object
Person1 = Person(“Alice”, 25)
Print(person1.greet())
Class Car:
Def __init__(self, brand=”Toyota”, model=”Corolla”):
Self.brand = brand
Self.model = model
Def details(self):
Return f”Car: {self.brand} {self.model}”
# Output:
# Car: Toyota Corolla
Page 9 of 12
# Car: Honda Civic
3. Inheritance in Classes
Class Animal:
Def __init__(self, name):
Self.name = name
Def sound(self):
Return “Some generic sound”
Class Dog(Animal):
Def sound(self): # Overriding parent method
Return “Bark”
Class Cat(Animal):
Def sound(self):
Return “Meow”
Dog = Dog(“Buddy”)
Cat = Cat(“Kitty”)
# Output:
# Buddy says: Bark
# Kitty says: Meow
Class BankAccount:
Def __init__(self, account_number, balance):
Self.account_number = account_number
Self.__balance = balance # Private attribute
Page 10 of 12
Def __hidden_method(self): # Private method
Return “This is a hidden method.”
# Creating an object
Account = BankAccount(“123456”, 1000)
5. Polymorphism in Classes
Class Bird:
Def fly(self):
Return “Some birds can fly”
Class Sparrow(Bird):
Def fly(self):
Return “Sparrows can fly high”
Class Penguin(Bird):
Def fly(self):
Return “Penguins cannot fly”
# Output:
# Sparrows can fly high
# Penguins cannot fly
# Some birds can fly
Page 11 of 12
Page 12 of 12