Python Unit 5
Python Unit 5
1.Positional Arguments:
Example:
return a + b
result = add_numbers(2, 3)
2.Keyword Arguments:
Example:
print(message)
#output
Hello, ajay!
3.Default Arguments:
Example:
print(result)#9
4.Variable-Length Arguments:
You can then use these arguments within the function as needed. Variable-
length arguments are useful when you want a function to be flexible in
terms of the number of arguments it can accept.
Example:
# Output:
In this example, the *args captures the positional arguments (1, 2, 3) into a
tuple, and **kwargs captures the keyword arguments (name="Alice",
age=25) into a dictionary.
Python module :
In Python, a module is a file containing Python definitions and statements. The file
name is the module name with the suffix .py appended. Modules allow you to
organize Python code into reusable units. You can use modules to break down
large programs into smaller, manageable pieces and to share code between
different programs.
Create a Module:
Save the following code in a file named my_module.py:
# my_module.py
def greet(name):
print(f"Hello, {name}!")
def square(x):
return x * x
Import the Module:
Now, in another Python script or interactive environment, you can import and use
the functions from your module:
# main_function.py
import my_module
my_module.greet("ajay")
result = my_module.square(5)
print(result)
Hello, ajay!
25
=> Alternatively, you can import specific functions from the module,
Method-2:
# main_script.py
from my_module import greet, square
greet("Bob")
result = square(3)
print(result)
# output
Hello, Bob!
9
=>Make sure that the module file (in this case, my_module.py) is in the same
directory as the script importing it or is in a directory listed in your Python path.
=>This is a basic example, and modules can become much more complex, with
classes, variables, and more. However, the fundamental idea remains the same: a
module is a file containing Python code that can be reused by other Python code.
Library:
Definition: A library in Python is a collection of modules, each of which contains
functions, classes, and constants that can be utilized in other Python scripts or
programs. Libraries are pre-written pieces of code that provide specific
functionalities, and they are designed to be reusable.
Example: NumPy, Matplotlib, and Pandas are examples of libraries in Python.
Each of them serves a specific purpose and provides functions and tools for tasks
such as numerical computing, data visualization, and data manipulation.
Example of python libraries :
1.NumPy :
NumPy is a powerful numerical computing library in Python. It provides support
for large, multi-dimensional arrays and matrices, along with a collection of
mathematical functions to operate on these elements. NumPy is a fundamental
package for scientific computing in Python and is widely used in various fields,
including data science, machine learning, engineering,
Example-1:
import numpy as np
# Simple array operations
arr = np.array([1, 2, 3, 4, 5])
# Square each element
squared_arr = np.square(arr)
print("Original Array:", arr)
print("Squared Array:", squared_arr)
#output
Original Array: [1 2 3 4 5]
Squared Array: [ 1 4 9 16 25]
Example-2:
import numpy as np
integer_array = np.array([1, 2, 3, 4, 5])
# Creating a new array by multiplying each element by 2
twice_array = 2 * integer_array
# Display the original and new arrays
print(integer_array)
print( twice_array)
#output
[1 2 3 4 5]
[ 2 4 6 8 10]
2.Matplotlib :Matplotlib is a comprehensive 2D plotting library for Python that
produces high-quality interactive and publication-ready visualizations. It provides
a wide variety of charts and plots for visualizing data.
Example-1
import matplotlib.pyplot as plt
# Example of a basic line plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Plot')
plt.show()
#output
example-2
import matplotlib.pyplot as plt
import numpy as np
# Simple line plot
x = np.array([1,2,3,4,5])
y = 2*x + 1
plt.plot(x, y)
plt.title('Simple Line Plot')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.show()
#output
Example-3
import matplotlib.pyplot as plt
categories = ['A', 'B', 'C']
values = [20, 35, 30]
# Create a bar chart
plt.bar(categories, values)
# Adding labels and title
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Simple Bar Chart')
# Display the chart
plt.show()
#output
Example-4
import matplotlib.pyplot as plt
import numpy as np
# Generate random data from a normal distribution
data = np.random.normal(170,10,250)
# Create a histogram
plt.hist(data, color='green', edgecolor='black')
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Histogram for Random Normal Distribution')
plt.show()
#output
3.Pandas :
Pandas is a powerful and popular open-source data manipulation and analysis
library for Python. It provides easy-to-use data structures and functions needed to
manipulate and analyze structured data seamlessly(exact matches). The primary
data structures in Pandas are the Series and DataFrame
Example:
import pandas as pd
# Creating a DataFrame from a dictionary
data = {'Name': ['ankit', 'Bob', 'ajay'],
'City': ['New York', 'lucknow', 'kanpur']
}
df = pd.DataFrame(data)
print(df)
# output
Name City
0 ankit New York
1 Bob lucknow
2 ajay Kanpur
4.TensorFlow:
TensorFlow is an open-source machine learning library developed by Google. It
facilitates the creation and training of machine learning models, particularly deep
learning models, through the use of computational graphs. TensorFlow allows
developers to define, optimize, and deploy machine learning models for a wide
range of applications, including image and speech recognition, natural language
processing, and more.
Example:
import tensorflow as tf
# Define TensorFlow constants
a = tf.constant(5)
b = tf.constant(3)
sum_result = a + b
product_result = a * b
print("Sum: ", sum_result.numpy())
print("Product:", product_result.numpy())
#output
Sum: 8
Product: 15
Example:
Tkinter:
Tkinter is the standard GUI (Graphical User Interface) library that comes
with Python.It provides a simple way to create windows, dialogs, buttons,
text boxes, and other GUI elements.Tkinter is easy to learn and is well-
suited for small to medium-sized applications.
Dynamic Typing:
In Python, variable types are determined at runtime. This means that the type of a
variable can change during the execution of a program. Interpreters allow this
flexibility, as they can dynamically allocate memory and interpret types as the
code is executed.
Read-Eval-Print Loop (REPL):
Python provides an interactive environment known as the REPL. This allows users
to enter Python code interactively, and the interpreter executes the code line by
line, providing immediate feedback.
Portability:
Since Python code is not compiled into machine-specific binaries, the same
Python code can run on different platforms without modification. The interpreter
handles the platform-specific details during execution.
Ease of Development:
The interpreted nature of Python simplifies the development process. Developers
can quickly test and debug code without the need for a separate compilation
step. This rapid development cycle is often cited as an advantage in the Python
ecosystem.
Platform Independence:
Python code can run on any platform with a compatible interpreter, making it
platform-independent. This is possible because the interpreter translates Python
code into intermediate bytecode, which is then executed by the Python Virtual
Machine (PVM).
Flexibility:
Interpreted languages are generally more flexible because they don't require a
separate compilation step before execution. This flexibility allows for features
such as dynamic loading of modules and runtime introspection.
Example with code :
# Simple Python code
a=5
b = 10
result = a + b
print("The result is:", result)
Private Heap Space:Python has its own space to store objects and data
structures.
Automatic Memory Management:Memory is automatically allocated and
deallocated, thanks to garbage collection.
Reference Counting:Objects have a reference count, and when it reaches zero,
the memory is freed.
Cycle Detector:Handles circular references to prevent memory leaks.
Memory Pools:Uses pools for efficient allocation of small objects.
Memory Manager (malloc and free):Utilizes system functions for memory
allocation and deallocation.
Memory Optimization Techniques:Includes strategies like memory block reuse
for efficiency.
gc Module:Provides a manual interface to the garbage collector when needed.
PEP 8:
PEP 8 is the Python Enhancement Proposal that provides style guide recommendations
for writing readable and maintainable Python code. The goal of PEP 8 is to enhance the
consistency of code written by different developers, making it easier to collaborate and
maintain codebases.
def print_even_str(str1):
words = str1.split()
for i in words:
if len(i) % 2 == 0:
print(i)
print_even_str(str1)
#output
Python
is
easy