0% found this document useful (0 votes)
3 views21 pages

Python Unit 5

The document discusses various argument-passing methods in Python, including positional, keyword, default, and variable-length arguments, with examples provided for each. It also explains the concept of modules and libraries in Python, highlighting their importance for code organization and reuse, along with examples of popular libraries like NumPy, Matplotlib, and Pandas. Additionally, it covers the definition of packages, Integrated Development Environments (IDEs), and GUI programming using Tkinter, including examples of Tkinter widgets.

Uploaded by

ys824708
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)
3 views21 pages

Python Unit 5

The document discusses various argument-passing methods in Python, including positional, keyword, default, and variable-length arguments, with examples provided for each. It also explains the concept of modules and libraries in Python, highlighting their importance for code organization and reuse, along with examples of popular libraries like NumPy, Matplotlib, and Pandas. Additionally, it covers the definition of packages, Integrated Development Environments (IDEs), and GUI programming using Tkinter, including examples of Tkinter widgets.

Uploaded by

ys824708
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
You are on page 1/ 21

Python unit-5

Q.1 discuss the different type of argument-passing methods in python.


Explain the variable length argument with any suitable example.?

In Python, arguments can be passed to functions using various methods,


each serving different purposes. The common argument-passing methods
are:

1.Positional Arguments:

This is the most straightforward method where arguments are passed


based on their position in the function call.

Example:

def add_numbers(a, b):

return a + b

result = add_numbers(2, 3)

2.Keyword Arguments:

Arguments are passed by explicitly specifying the parameter names along


with their values.

Example:

def greet(name, greeting):

return f"{greeting}, {name}"

message = greet(name="ajay", greeting="Hello")

print(message)

#output

Hello, ajay!
3.Default Arguments:

Default values are assigned to parameters, making them optional during


function calls.

Example:

def power(base, exponent=2):

return base ** exponent

result = power(3) # Uses the default exponent of 2

print(result)#9

4.Variable-Length Arguments:

Python supports variable-length arguments using the *args and **kwargs


syntax.

*arg1 allows a function to accept any number of positional arguments, and


they are captured in a tuple.

**arg2 allows a function to accept any number of keyword arguments, and


they are captured in a dictionary.

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:

def variable_args_example(*arg1, **arg2):

print("Positional arguments (tuple) is ", arg1)

print("Keyword arguments (dictionary):", arg2)

variable_args_example(1, 2, 3, name="Alice", age=25)

# Output:

# Positional arguments (tuple) is (1, 2, 3)


# Keyword arguments (dictionary) is {'name': 'Alice', 'age': 25}

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

5.SciPy: SciPy is an open-source library for scientific and technical computing in


Python. It extends the capabilities of NumPy by providing additional modules for
optimization, integration, interpolation, linear algebra, signal and image
processing, statistical functions, and more. SciPy is widely used in scientific
research, engineering, and various fields that require advanced numerical and
computational capabilities.
6.PyTorch:
PyTorch is an open-source machine learning library for Python that provides tools
for building and training deep learning models. It offers dynamic computational
graphs, allowing developers to modify models on-the-fly, making it especially
suitable for research and experimentation. PyTorch is widely used in various
domains, including computer vision, natural language processing, and
reinforcement learning.
7.PyBrain:
PyBrain was an open-source machine learning library for Python. It was designed
to provide flexible and easy-to-use tools for the implementation of various
machine learning algorithms, with a focus on neural networks. PyBrain allowed
users to experiment with different algorithms and models, making it a popular
choice for educational purposes and research in artificial intelligence.
8.Pygame:
Pygame is a cross-platform set of Python modules designed for writing video
games. It provides functionality for managing graphics, handling user input,
playing sounds, and more. Pygame is built on top of the Simple DirectMedia Layer
(SDL), making it a versatile choice for creating 2D games.
9.Scrapy:
Scrapy is an open-source and collaborative web crawling framework for Python. It
provides a set of tools and abstractions to facilitate the extraction of data from
websites. Scrapy allows developers to create spiders, which are scripts that define
how to navigate a website, extract desired information, and optionally store or
process the data. With features like automatic request throttling, middleware
support, and an interactive shell for testing, Scrapy simplifies the process of web
scraping and data extraction, making it a popular choice for various web crawling
applications.

Package: new topic


Definition: A package in Python is a way of organizing related modules into a
single directory hierarchy. A package can contain sub-packages, modules, and
other resources. Packages are used to create a modular and hierarchical structure
in Python projects, making it easier to manage and organize code.
Example: The numpy library is an example of a package. Within the numpy
package, you have sub-packages like numpy.random and numpy.linalg, along with
various modules containing functions and classes. The package structure helps
organize functionality into logical units.
Libraries and packages are essential components of the Python ecosystem,
enabling code reuse, modularity, and efficient development in various domains.

Integrated Development Environment (IDE) : new topic


An Integrated Development Environment (IDE) is a software application that
provides comprehensive facilities to computer programmers for software
development. It typically includes a source code editor, debugger, build
automation tools, and often incorporates features like code completion, syntax
highlighting, and project management.
Key components and features of an IDE include:
Code Editor: A text editor that allows programmers to write, edit, and manage
source code for software development.
Debugger: A tool that helps in finding and fixing errors or bugs in the code by
allowing step-by-step execution, setting breakpoints, and inspecting variable
values.
Compiler/Interpreter Integration: IDEs often integrate with compilers or
interpreters for the programming language, allowing developers to build and run
their code directly within the development environment.
Build Automation: Tools for automating the process of compiling, linking, and
building the final executable or deployable package of the software.
Syntax Highlighting: The highlighting of syntax elements in the code editor to
enhance code readability.
Code Completion: Intelligent code suggestions and autocompletion to speed up
the coding process.
Error Highlighting: Instant feedback on syntax errors or other issues in the code
through visual cues in the editor.
There are some IDE are :
PyCharm: PyCharm is a powerful IDE developed by JetBrains specifically for
Python development. It provides features like code completion, intelligent code
analysis, debugging support, and integrated testing.
Jupyter Notebooks: Jupyter Notebooks are an open-source web application that
allows you to create and share documents containing live code, equations,
visualizations, and narrative text. They are widely used for data science and
interactive computing.
VSCode (Visual Studio Code):VSCode is a lightweight, open-source code editor
developed by Microsoft. It supports Python through extensions and provides
features like IntelliSense, debugging support, and version control integration.
Spyder:Spyder is an open-source IDE designed for scientific computing and data
analysis. It comes with built-in tools for exploring and analyzing data, making it
suitable for tasks in fields such as machine learning and numerical computing.
IDLE (Integrated Development and Learning Environment):IDLE is the default IDE
that comes bundled with the Python programming language. It provides basic
features like an interactive shell, code editor, and debugger.
Anaconda: Anaconda is a distribution of Python and other scientific computing
packages. While it includes Jupyter Notebooks and Spyder, it also provides its own
IDE, Anaconda Navigator, for managing environments and packages.
Eric IDE: Eric IDE is an open-source Python IDE written in PyQt. It offers features
such as project management, integrated debugger, and support for web
development with Django.

GUI programming : new topic

GUI programming, which stands for Graphical User Interface programming,


refers to the process of creating software applications that feature graphical
elements and interactive components to allow users to interact with the
program. Unlike command-line interfaces (CLIs) that rely on text-based
commands, GUIs use graphical elements such as windows, icons, buttons,
and menus to enhance user experience and make software more visually
intuitive.

=> Popular programming languages for GUI development include Java


(Swing, JavaFX), Python (Tkinter, PyQt, PySide), C# (Windows Forms, WPF),
and others. GUI programming is utilized in a wide range of software
applications, including desktop applications, mobile apps, web applications,
and more.

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.

Q. W.A.P to print “hello world” using Tkinter ?

# code of Tkinter example:


import tkinter as tk
# Create the main window
window = tk.Tk()
# Create a label widget and add it to the window
label = tk.Label(window, text="Hello world",)
# Pack the label into the window
label.pack()
# Run the Tkinter event loop
window.mainloop()
#output
Hello world
=> when you run this code, it should display a simple window with the label "Hello
world!!".

Tkinter widgets : new topic


In the context of graphical user interfaces (GUIs) and software
development, a "widget" refers to a graphical element or user interface
component that users can interact with. Widgets are the building blocks of
a GUI and can include various elements such as buttons, text boxes, labels,
checkboxes, radio buttons, sliders, and more.
Label:A Tkinter widget used to display text or images on the GUI.
label = Label(root, text="Hello, Tkinter!")
Button: A clickable Tkinter widget that triggers a specified function when pressed.
import tkinter as tk
def f1():
print("Button clicked!")
root = tk.Tk()
button = tk.Button(root, text="Click me", command=f1, fg="blue")
button.pack()
root.mainloop()
Entry: A Tkinter widget that provides a single-line text entry box for user input.
import tkinter as tk
root = tk.Tk()
entry = tk.Entry(root, fg="red") # for user input
entry.pack()
root.mainloop()
Text: A Tkinter widget that allows multi-line text entry and display.
text_widget = Text(root)
Frame:A container Tkinter widget used for organizing and grouping other widgets.
import tkinter as tk
def abc():
label.config(text="Button clicked!")
root = tk.Tk()
root.title("Frame Example")
frame = tk.Frame(root, padx=20, pady=20)
frame.pack()
label = tk.Label(frame, text="Hello, Tkinter!")
button = tk.Button(frame, text="Click me!", command=abc)
label.pack()
button.pack()
root.mainloop()
Canvas:A Tkinter widget that serves as a drawing surface for creating shapes,
images, and custom graphics.
canvas = Canvas(root, width=300, height=200)
Checkbutton:A Tkinter widget representing a checkbox that can be either
selected or deselected.
check_button = Checkbutton(root, text="Check me")
Radiobutton:A Tkinter widget used to create a group of radio buttons, where only
one button in the group can be selected at a time.
radio_button = Radiobutton(root, text="Option 1", value=1,
variable=selected_option)
Listbox:A Tkinter widget providing a list from which the user can select one or
more items.
listbox = tk.Listbox(root)
Scrollbar:A Tkinter widget that enables scrolling through content, typically used
with other widgets like Text or Listbox.
scrollbar = Scrollbar(root, command=text_widget.yview)
code example Tkinter:
import tkinter as tk
def on_checkbutton_click():
if check_var.get():
label.config(text="Checkbutton is checked")
else:
label.config(text="Checkbutton is unchecked")
root = tk.Tk()
root.title("Checkbutton Example")
check_var = tk.IntVar()
checkbutton = tk.Checkbutton(root, text="Check me!", variable=check_var,
command=on_checkbutton_click)
# Create a Label
label = tk.Label(root, text="Checkbutton status will be displayed here")
# Pack the Checkbutton and Label into the main window
checkbutton.pack()
label.pack()
root.mainloop()
Q. Explain why python is considered an interpreted language.?
Python is considered an interpreted language primarily because it executes
code line by line at runtime, rather than being compiled into machine code
before execution.
The key characteristics that contribute to Python being an interpreted language are:

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)

Memory management in Python:


Memory management in Python is primarily managed by the Python memory manager,
which handles the allocation and deallocation of memory for Python objects. Python
uses a combination of techniques, including automatic memory management through
garbage collection and a private heap space for managing memory.

Here are key aspects of memory management in Python:

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.

Here are some key points from PEP 8:

Indentation:Use 4 spaces per indentation level.


Maximum Line Length:Limit code lines to 79 characters and
docstrings/comments to 72.
Imports:Grouped by standard library, third-party, and own modules. Sorted
alphabetically.
Whitespace:Avoid extra spaces inside parentheses, brackets, and before commas,
semicolons, or colons.
Comments:Use sparingly. Should be complete sentences, explaining complex
code.
Naming Conventions:Lowercase with underscores for functions/variables
(function_name).
Documentation Strings:Use triple double-quotes (""") for docstrings.
Q. w.a.p to print even length words in a string ?

def print_even_str(str1):

words = str1.split()

for i in words:

if len(i) % 2 == 0:

print(i)

str1 = "Python is fun and easy"

print_even_str(str1)

#output

Python
is

easy

You might also like