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

Pythonexameple Code for Builtins Fumctipns

The document provides example codes for various Python built-in functions, iterators, data visualization using Matplotlib, machine learning with Scikit-learn, and concepts of polymorphism and classes. It includes code snippets demonstrating the usage of functions like abs(), len(), and max(), as well as examples of creating and using iterators, visualizing data, and implementing machine learning models. Additionally, it covers class definitions, inheritance, encapsulation, and polymorphism in Python.

Uploaded by

harishmaakshaya
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)
19 views

Pythonexameple Code for Builtins Fumctipns

The document provides example codes for various Python built-in functions, iterators, data visualization using Matplotlib, machine learning with Scikit-learn, and concepts of polymorphism and classes. It includes code snippets demonstrating the usage of functions like abs(), len(), and max(), as well as examples of creating and using iterators, visualizing data, and implementing machine learning models. Additionally, it covers class definitions, inheritance, encapsulation, and polymorphism in Python.

Uploaded by

harishmaakshaya
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/ 12

PYTHON EXAMPLE CODE FOR BUILTINS FUNCTION

Here are some example codes for common Python built-in functions:

1. abs() – Absolute Value


print(abs(-10)) # Output: 10

2. len() – Length of an Object


my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # Output: 5

3. max() – Maximum Value


numbers = [10, 20, 30, 40]
print(max(numbers)) # Output: 40

4. min() – Minimum Value


print(min(numbers)) # Output: 10

5. sum() – Sum of Elements


print(sum(numbers)) # Output: 100

6. round() – Rounds a Number


print(round(3.14159, 2)) # Output: 3.14

7. sorted() – Sorts a List


nums = [5, 3, 8, 1]
print(sorted(nums)) # Output: [1, 3, 5, 8]

8. type() – Data Type of an Object


print(type(10)) # Output: <class 'int'>
print(type(3.14)) # Output: <class 'float'>
print(type("Hello")) # Output: <class 'str'>

9. str(), int(), float() – Type Conversion


print(str(100)) # Output: '100'
print(int("10")) # Output: 10
print(float("3.5")) # Output: 3.5

10. zip() – Combine Two Lists


names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
combined = zip(names, ages)
print(list(combined)) # Output: [('Alice', 25), ('Bob', 30), ('Charlie', 35)]

Page 1 of 12
PYTHON EXAMPLE CODE FOR ITETATORS

Here are some examples of iterators in Python:

1. Using an Iterator with iter() and next()


my_list = [10, 20, 30, 40]
iterator = iter(my_list) # Convert list to an iterator

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

2. Using an Iterator in a for Loop


my_tuple = ("apple", "banana", "cherry")
for item in iter(my_tuple):
print(item)
# Output:
# apple
# banana
# cherry

3. Creating a Custom Iterator (Using a Class)


class Counter:
def __init__(self, start, end):
self.current = start
self.end = end

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

4. Using iter() with a Sentinel Value


with open("sample.txt", "r") as file:
for line in iter(file.readline, ''): # Stops when '' (empty string) is returned
print(line.strip()) # Remove newline characters

5. Using iter() with a Callable Function


import random

def random_number():
return random.randint(1, 10)

iterator = iter(random_number, 7) # Keeps calling random_number() until it returns 7


for num in iterator:
print(num)

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

If you haven't installed it yet, run:

pip install matplotlib

2. Simple Line Plot


import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]

plt.plot(x, y, marker='o', linestyle='-', color='b', label="Line 1")


plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.title("Simple Line Plot")
plt.legend()
plt.show()

3. Bar Chart
categories = ["A", "B", "C", "D"]
values = [10, 20, 15, 25]

plt.bar(categories, values, color=['red', 'blue', 'green', 'purple'])


plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Bar Chart Example")
plt.show()

4. Scatter Plot
import numpy as np

x = np.random.rand(50)
y = np.random.rand(50)

plt.scatter(x, y, color='g', marker='x')


plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.title("Scatter Plot Example")
plt.show()

5. Histogram
data = np.random.randn(1000) # Generate random data

plt.hist(data, bins=30, color='orange', edgecolor='black')


plt.xlabel("Value")
plt.ylabel("Frequency")
plt.title("Histogram Example")
plt.show()

6. Pie Chart
labels = ["Python", "Java", "C++", "JavaScript"]
sizes = [40, 30, 15, 15]
colors = ["blue", "red", "green", "purple"]

plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140)


plt.title("Programming Language Popularity")
plt.show()

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

2. Load Dataset (Iris Example)

From sklearn import datasets

Iris = datasets.load_iris()
X = iris.data
Y = iris.target

Print(“Feature Names:”, iris.feature_names)


Print(“Target Names:”, iris.target_names)
Print(“Dataset Shape:”, X.shape)

3. Splitting Data into Train and Test Sets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

Print(“Training Set Shape:”, X_train.shape)


Print(“Testing Set Shape:”, X_test.shape)

.Standardizing Data

Page 4 of 12
Scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

4. Train a Machine Learning Model (Logistic Regression)

Model = LogisticRegression()
Model.fit(X_train, y_train)

Y_pred = model.predict(X_test)

Accuracy = accuracy_score(y_test, y_pred)


Print(“Accuracy:”, accuracy)

5. Using a Different Model (Random Forest)

From sklearn.ensemble import RandomForestClassifier

Rf_model = RandomForestClassifier(n_estimators=100, random_state=42)


Rf_model.fit(X_train, y_train)

Y_pred_rf = rf_model.predict(X_test)

Accuracy_rf = accuracy_score(y_test, y_pred_rf)


Print(“Random Forest Accuracy:”, accuracy_rf)

6. Clustering Example (K-Means)

From sklearn.cluster import Kmeans

Kmeans = Kmeans(n_clusters=3, random_state=42)


Clusters = kmeans.fit_predict(X)

Print(“Cluster Labels:”, np.unique(clusters))

7. Model Evaluation (Confusion Matrix)


Page 5 of 12
From sklearn.metrics import confusion_matrix

Conf_matrix = confusion_matrix(y_test, y_pred_rf)


Print(“Confusion Matrix:\n”, conf_matrix)

8. Regression Example (Linear Regression)

From sklearn.linear_model import LinearRegression

# 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.

1. Polymorphism with Functions

A single function can handle different data types or objects.

print(len("Hello")) # Output: 5 (length of string)


print(len([1, 2, 3, 4])) # Output: 4 (length of list)
print(len({"a": 1, "b": 2})) # Output: 2 (length of dictionary)

2. Polymorphism with Class Methods

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()]

for animal in animals:


print(animal.speak())

# Output:
# Woof!
# Meow!

3. Polymorphism with Inheritance

A child class can override a method from the parent class.

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()]

for animal in animals:


print(animal.make_sound())

# Output:
# Bark
# Meow
# Some sound

4. Polymorphism with Abstract Classes (abc Module)

Abstract classes ensure that child classes implement specific methods.

from abc import ABC, abstractmethod

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

shapes = [Circle(5), Square(4)]


for shape in shapes:
print(shape.area())

# 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).

1. Basic Class Example

Class Person:
Def __init__(self, name, age): # Constructor
Self.name = name
Self.age = age

Def greet(self): # Method


Return f”Hello, my name is {self.name} and I am {self.age} years old.”

# Creating an object
Person1 = Person(“Alice”, 25)
Print(person1.greet())

# Output: Hello, my name is Alice and I am 25 years old.

2. Class with Default Values

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}”

# Object with default values


Car1 = Car()
Print(car1.details())

# Object with custom values


Car2 = Car(“Honda”, “Civic”)
Print(car2.details())

# 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”)

Print(dog.name, “says:”, dog.sound())


Print(cat.name, “says:”, cat.sound())

# Output:
# Buddy says: Bark
# Kitty says: Meow

4. Encapsulation (Private Variables and Methods)

Class BankAccount:
Def __init__(self, account_number, balance):
Self.account_number = account_number
Self.__balance = balance # Private attribute

Def deposit(self, amount):


If amount > 0:
Self.__balance += amount
Return f”Deposited {amount}. New balance: {self.__balance}”

Page 10 of 12
Def __hidden_method(self): # Private method
Return “This is a hidden method.”

# Creating an object
Account = BankAccount(“123456”, 1000)

# Accessing public method


Print(account.deposit(500))

# Trying to access private attribute (will raise an error)


# print(account.__balance) # AttributeError

# Trying to access private method (will raise an error)


# print(account.__hidden_method()) # AttributeError

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”

Birds = [Sparrow(), Penguin(), Bird()]


For bird in birds:
Print(bird.fly())

# Output:
# Sparrows can fly high
# Penguins cannot fly
# Some birds can fly

Page 11 of 12
Page 12 of 12

You might also like