0% found this document useful (0 votes)
396 views122 pages

Python U 5 One Shot Notes - 080fb705 335c 4bee Afc8 Ee7a01d3a11e

The document discusses Python packages and modules. It defines a Python package as a folder containing various modules as files. It provides steps to create a Python package, including creating a folder, adding an empty __init__.py file, and adding module files. The __init__.py file helps Python recognize the folder as a package and can specify which functions to import from each module. Modules are files that contain built-in functions, classes and variables that can be reused across programs to organize code. Popular Python libraries like NumPy, Pandas and Matplotlib are also discussed.

Uploaded by

kr387767
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)
396 views122 pages

Python U 5 One Shot Notes - 080fb705 335c 4bee Afc8 Ee7a01d3a11e

The document discusses Python packages and modules. It defines a Python package as a folder containing various modules as files. It provides steps to create a Python package, including creating a folder, adding an empty __init__.py file, and adding module files. The __init__.py file helps Python recognize the folder as a package and can specify which functions to import from each module. Modules are files that contain built-in functions, classes and variables that can be reused across programs to organize code. Popular Python libraries like NumPy, Pandas and Matplotlib are also discussed.

Uploaded by

kr387767
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/ 122

PYTHON PROGRAMMING

UNIT -5: PYTHON PACKAGES


ONE SHOT

Today’s Target

 MOST IMPORTANT QUESTIONS


By PRAGYA RAJVANSHI
 AKTU PYQs B.Tech, M.Tech( C.S.E)
AKTU PYQs : Unit-5
Q1 What is python package ? List various step to create a python package

Q2 What is use of _int_.py in python

Q3 What is python module? how to create and import module in python

Q4 What is the significance of module in python? What are the methods of importing a module? Explain with
suitable example
Q5 What is the python libraries? List some of the important python libraries

Q6 How can you create python file that can be imported as a library as well as a standalone script

Q7 Difference between import library and from library import*

Q8 Define matplotlib. List some built-in function

Q9 Write a program to plot a simple line graph using matplotlib

Q10 Create a bar chart using matplotlib to represent darta


AKTU PYQs : Unit-5
Q11 Create a histogram using matplotlib

Q12 Define Numpy . List some built-in function in NUMPY

Q13 Write a numpy program to create a 2 d array of sizw2*3 (composed of 4 byte integer elements), also print
the shape, size, type and data type of the array

Q14 Define pandas. List some built-in function in Pandas

Q15 Define Pandas Data frame. How do you create a pandas Data frame

Q16 How do you select rows and columns from Panda data frame

Q17 What is tkinter and why it is used in python programming

Q18 How do you create basic window using tkinter?

Q19 What are the widgets in tkinter and can you give example of some commonly used widget
AKTU PYQs : Unit-5
Q20 Define function and write its advantages

Q21 How to define and call function in python? explain different parts of a function

Q22 Discuss the different types of arguments passing methods in python.wxpalin the variable length
argument with any suitable example

Q23 Discuss the scope rule in python

Q24 Discuss the function in python with its parts and scope .Explain with example (take simple calculator with
add, sub, division and multiplication)
Q25 Write apython function remvekth(s,k) that take s as a input string and a n integer k>=0 and removes the
character at a index k. if k is beyond the length of s , the whole os string is returned
removekth(“PYTHON”,1) return PTHON
removekth(“PYTHON”,3) return PYTON
removekth(“PYTHON”,20) return PYTHON
AKTU PYQs : Unit-5
Q26 Write a python code to find out occurrence of an elements in a list

Q27 Write a python function, searchMany(s,x,k) that takes an argument a sequence s and
integersx,k(k>0) the function return true if there are at most k occurrence of x in s .otherwise it
return false
searchMany([10,17,15,12],15,1) return true, searchMany([10,12,12,12],12,2) return false

Q28 What is decorators?


Python Packages

 We usually organize our files in different folders and subfolders based on some criteria, so
that they can be managed easily and efficiently. For example, we keep all our games in a
Games folder and we can even subcategorize according to the genre of the game or
something like that. The same analogy is followed by the packages in Python.
 What is a Python Package?
 Python modules may contain several classes, functions, variables, etc. whereas Python
packages contain several modules. In simpler terms, a Package in Python is a folder that
contains various modules as files.
Creating Package

 Let’s create a package in Python named mypckg that will contain two modules mod1 and
mod2. To create this module follow the below steps:
 Create a folder named mypckg.
 Inside this folder create an empty Python file i.e. __init__.py
 Then create two modules mod1 and mod2 in this folder.
 mod1.py
 def gfg():
 print("Welcome to GFG")
 mod2.py
 def sum(a, b):
 return a+b
The Hierarchy of our Python package looks like this:
Understanding __init__.py

 __init__.py helps the Python interpreter recognize the folder as a package. It also specifies
the resources to be imported from the modules. If the __init__.py is empty this means that all
the functions of the modules will be imported. We can also specify the functions from each
module to be made available.
 For example, we can also create the __init__.py file for the above module as:
 __init__.py
 from .mod1 import gfg
 from .mod2 import sum
 This __init__.py will only allow the gfg and sum functions from the mod1 and mod2 modules to
be imported
We will import the modules from the above-created package and
will use the functions inside those modules

 from mypckg import mod1


 from mypckg import mod2
 mod1.gfg()
 res = mod2.sum(1, 2)
 print(res)
 OUTPUT
 Welcome to GFG
 3
We can also import the specific function also using the same syntax

 from mypckg.mod1 import gfg


 from mypckg.mod2 import sum
 gfg()
 res = sum(1, 2)
 print(res)
 OUTPUT
 Welcome to GFG
 3
Python Modules

 Python Module is a file that contains built-in functions, classes, and variables. There are many
Python modules, each with its specific work,
 A Python module is a file containing Python definitions and statements. A module can define
functions, classes, and variables. A module can also include runnable code.
 Grouping related code into a module makes the code easier to understand and use. It also
makes the code logically organized
 The significance of Modules is as follows:
 It reduces the complexity of programs.
 Its content can be reused in other programs, without having to rewrite them.
 It creates a number of well-defined, documented boundaries within the program.
Create a Python Module

 To create a Python module, write the desired code and save that in a file with .py extension.
Import module in Python

 We can import the functions, and classes defined in a module to another module using the
import statement in some other Python source file.
 When the interpreter encounters an import statement, it imports the module if the module is
present in the search path
 Note: A search path is a list of directories that the interpreter searches for importing a
module.
 Syntax to Import Module in Python
 import module
Different methods of importing a module

 Importing modules
 Import Specific Attributes from a Python module
 Import the whole module and rename it, usually using a shorter variable name:
 import specific things from the module and rename them as you're importing them
1. Importing modules
2.Import Specific Attributes from a Python module
3. Import the whole module and rename it, usually using a shorter
variable name:
4.import specific things from the module and rename them as you're
importing them
Python Library
 Normally, a library is a collection of books or a room or place where many books are stored to be used later. Similarly,
in the programming world, a library is a collection of precompiled codes that can be used later on in a program for
some specific well-defined operations. Other than pre-compiled codes, a library may contain documentation,
configuration data, message templates, classes, values, etc.
 A Python library is a collection of related modules. It contains bundles of code that can be used repeatedly in
different programs. It makes Python Programming simpler and more convenient for the programmer. As we don’t
need to write the same code again and again for different programs. Python libraries play a very vital role in fields of
Machine Learning, Data Science, Data Visualization, etc
 As stated above, a Python library is simply a collection of codes or modules of codes that we can use in a program for
specific operations. We use libraries so that we don’t need to write the code again in our program that is already
available. But how it works? Actually, in the MS Windows environment, the library files have a DLL extension
(Dynamic Load Libraries). When we link a library with our program and run that program, the linker automatically
searches for that library. It extracts the functionalities of that library and interprets the program accordingly
Python standard library

 The Python Standard Library contains the exact syntax, semantics, and tokens of Python. It contains
built-in modules that provide access to basic system functionality like I/O and some other core
modules. Most of the Python Libraries are written in the C programming language. The Python
standard library consists of more than 200 core modules. All these work together to make Python a
high-level programming language. Python Standard Library plays a very important role. Without it, the
programmers can’t have access to the functionalities of Python. But other than this, there are several
other libraries in Python that make a programmer’s life easier. Let’s have a look at some of the
commonly used libraries
Python standard library

1.TensorFlow: This library was developed by Google in collaboration with the Brain Team. It is an open-
source library used for high-level computations(dot product, addition, exponent, division etc). It is also used
in machine learning and deep learning algorithms. It contains a large number of tensor operations.
Researchers also use this Python library to solve complex computations in Mathematics and Physics.
2.Matplotlib: This library is responsible for plotting numerical data. And that’s why it is used in data
analysis. It is also an open-source library and plots high-defined figures like pie charts, histograms,
scatterplots, graphs, etc
3.Pandas: Pandas are an important library for data scientists. It is an open-source machine learning library
that provides flexible high-level data structures and a variety of analysis tools. It eases data analysis, data
manipulation, and cleaning of data. Pandas support operations like Sorting, Re-indexing, Iteration,
Concatenation, Conversion of data, Visualizations, Aggregations, etc.
Python standard library

4. Numpy: The name “Numpy” stands for “Numerical Python”. It is the most commonly used library. It is a
popular machine-learning library that supports large matrices and multi-dimensional data. It consists of in-
built mathematical functions for easy computations. Even libraries like Tensor Flow use Numpy internally to
perform several operations on tensors. Array Interface is one of the key features of this library
5.SciPy: The name “SciPy” stands for “Scientific Python”. It is an open-source library used for high-level
scientific computations. This library is built over an extension of Numpy. It works with Numpy to handle
complex computations. While Numpy allows sorting and indexing of array data, the numerical data code is
stored in SciPy. It is also widely used by application developers and engineers.
6. Scrapy: It is an open-source library that is used for extracting data from websites. It provides very fast
web crawling(automatically accessing a website and obtaining data via software program) and high-level
screen scraping. It can also be used for data mining and automated testing of data.
Python standard library
7. Scikit-learn: It is a famous Python library to work with complex data. Scikit-learn is an open-source library
that supports machine learning. It supports various supervised and unsupervised algorithms like linear
regression, classification, clustering, etc. This library works in association with Numpy and SciPy.
8.PyGame: This library provides an easy interface to the Standard Directmedia Library (SDL) platform-
independent graphics, audio, and input libraries. It is used for developing video games using computer
graphics and audio libraries along with Python programming language.
9.PyTorch: PyTorch is the largest machine learning library that optimizes tensor computations. It has rich
APIs to perform tensor computations with strong GPU acceleration. It also helps to solve application issues
related to neural networks.
10.PyBrain: The name “PyBrain” stands for Python-based Based Reinforcement Learning, Artificial
Intelligence, and Neural Networks library. It is an open-source library built for beginners in the field of
Machine Learning. It provides fast and easy-to-use algorithms for machine-learning tasks. It is so flexible
and easily understandable and that’s why is helpful for developers that are new in research fields
DIFFERENCE BETWEEN-

S.NO Import library From library import*

1 Python import loads a python module/library From loads a python module into the
into its own namespace current name space

2 By using import , we include all the codes inside We includes all the code or only the
the module or library required function , classes present inside
the module or library
3 Dot operator is used Dot operator is not required

4 It is required to mention the module name It is not needed to mention the module
followed by dot to access any names in the name to access any names in the module
module
5
DIFFERENCE BETWEEN-
S.NO Import library From library import*
Python Numpy

 Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional


array object and tools for working with these arrays. It is the fundamental package for scientific
computing with Python
 Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of
positive integers. In Numpy, several dimensions of the array are called the rank of the array.
 A tuple of integers giving the size of the array along each dimension is known as the shape of the array.
An array class in Numpy is called ndarray.
 Elements in Numpy arrays are accessed by using square brackets and can be initialized by using nested
Python Lists.
Python Numpy
Python PIP

 Package refers to a distribution of Python code that includes one or more modules or libraries. These
packages are typically published on the Python Package Index (PyPI) and can be easily installed using
pip.
 Python packages may contain modules, sub-packages, and additional resources such as documentation
and data files
 Python PIP is the package manager for Python packages. We can use PIP to install packages that do not
come with Python
Plotting with Matplotlib in Python

 Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-
platform data visualization library built on NumPy arrays and designed to work with the broader SciPy
stack. It was introduced by John Hunter in the year 2002. One of the greatest benefits of visualization is
that it allows us visual access to huge amounts of data in easily digestible visuals. Matplotlib consists of
several plots like line, bar, scatter, histogram, etc.
 Installation: Windows, Linux, and macOS distributions have Matplotlib and most of its dependencies as
wheel packages. Run the following command to install the Matplotlib package. But before that make
sure Python and PIP are already installed on a system
Plotting with Matplotlib in Python

 After checking Python and PIP in your system, You need to run this command to install Matplotlib.
 python -m pip install -U matplotlib
 Importing Matplotlib
 After successfully installing Matplotlib, You can use this command to import Matplotlib on your system.
 import matplotlib
Types of Matplotlib

 Matplotlib comes with a wide variety of plots. Plots help to understand trends, and patterns, and to
make correlations. They’re typically instruments for reasoning about quantitative information. Some of
the sample plots are covered here.
 Matplotlib Line Plot
 Matplotlib Bar Plot
 Matplotlib Histograms Plot
 Matplotlib Scatter Plot
 Matplotlib Pie Charts
 Matplotlib Area Plot
Matplotlib Line Plot
 By importing the matplotlib module, defines x and y values for a plotPython, plots the data using the
plot() function and it helps to display the plot by using the show() function . The plot() creates a line plot
by connecting the points defined by x and y values.
Matplotlib Line Plot
Matplotlib Bar Plot
 By using matplotlib library in Pythontwo, it allows us to access the functions and classes provided by the
library for plotting. There are tow lists x and y are defined . This function creates a bar plot by taking x-
axis and y-axis values as arguments and generates the bar plot based on those value.
Matplotlib Bar Plot
Matplotlib Histograms Plot
 By using the matplotlib module defines the y-axis values for a histogram plot. Plots in the ,histogram
using the hist() function and displays the plot using the show() function. The hist() function creates a
histogram plot based on the values in the y-axis list.
Matplotlib Histograms Plot
Matplotlib Scatter Plot
 By imports, plot the matplotlib module, define x and y values for a scatter plot, plots the data using the
scatter() function, and displays the plot using the show() function. The scatter() function creates a
scatter plot by plotting individual data points defined by the x and y values
Matplotlib Scatter Plot
Matplotlib Pie Charts
 By importing the module Matplotlib in Python to create a pie chart with three categories and respective
sizes. The plot .pie() function is used to generate the chart, including labels, percentage formatting, and
a starting angle.
 A title is added with plt. title(), and plt. show() displays the resulting pie chart, visualizing the
proportional distribution of the specified categories.
Matplotlib Pie Charts
Matplotlib Area Plot
 By importing Matplotlib we sky blue generated an area chart with two lines (‘Line 1’ and ‘Line 2’). The
area between the lines is shaded in a sky-blue color with 40% transparency.
 The x-axis values are in the list ‘x’, and the corresponding y-axis values for each line are in ‘y1’ and ‘y2’.
Labels, titles legends, and legends are added, and the resulting area chart is displayed.
Matplotlib Area Plot
Matplotlib Area Plot
Numpy Functions in Python
 1.np.array(): This function is used to create an array in NumPy.
Numpy Functions in Python
 2.np.arange(): This function is used to create an array with a range of values.
Numpy Functions in Python
 3.np.zeros(): This function is used to create an array filled with zeros
Numpy Functions in Python
 4.np.ones(): This function is used to create an array filled with ones.
Numpy Functions in Python
 5.Numpy.square: This mathematical function helps user to calculate square value of each element in
the array
Numpy Functions in Python
 6. np.random.rand(): This function is used to create an array with random values between 0 and 1.
Numpy Functions in Python
 7. np.random.randint(): This function is used to create an array with random integer values between a
specified range.
Numpy Functions in Python
 8. np.max(): This function is used to find the maximum value in an array
Numpy Functions in Python
 9.np.min(): This function is used to find the minimum value in an array
Numpy Functions in Python
 10 np.mean(): This function is used to find the mean value of an array
Numpy Functions program
 Write a numpy program to create a 2 d array of size2*3 (composed of 4 byte integer elements), also print
the shape, size, type and data type of the array
What is Pandas?

 Pandas is a powerful and versatile library that simplifies tasks of data manipulation in Python.
 Pandas is built on top of the NumPy library and is particularly well-suited for working with tabular data,
such as spreadsheets or SQL tables.
 Its versatility and ease of use make it an essential tool for data analysts, scientists, and engineers
working with structured data in Python.
 What can you do using Pandas?
 Pandas are generally used for data science but have you wondered why? This is because pandas are
used in conjunction with other libraries that are used for data science. It is built on the top of the
NumPy library which means that a lot of structures of NumPy are used or replicated in Pandas.
 The data produced by Pandas are often used as input for plotting functions of Matplotlib, statistical
analysis in SciPy, and machine learning algorithms in Scikit-learn. Here is a list of things that we can do
using Panda Data set cleaning, merging, and joining.
What is Pandas?

 Easy handling of missing data (represented as NaN) in floating point as well as non-floating point data.
 Columns can be inserted and deleted from Data Frame and higher dimensional objects.
 Powerful group by functionality for performing split-apply-combine operations on data sets.
 Data Visualization
Getting Started with Pandas

Installing Pandas
 The first step of working with pandas is to ensure whether it is installed in the system or not. If not
then we need to install it in our system using the pip command. Type the cmd command in the search
box and locate the folder using the cd command where the python-pip file has been installed. After
locating it, type the command:
 pip install pandas
Getting Started with Pandas

Importing Pandas
 After the pandas have been installed into the system, you need to import the library. This module is
generally imported as follows:
 import pandas as pd
 Here, pd is referred to as an alias to the Pandas. However, it is not necessary to import the library using
the alias, it just helps in writing less amount code every time a method or property is called.
Pandas Data Structures

 Pandas generally provide two data structures for manipulating data, They are:
 Series, DataFrame
 Pandas Series
 A Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer, string,
float, python objects, etc.). The axis labels are collectively called indexes.
 Pandas Series is nothing but a column in an Excel sheet. Labels need not be unique but must be a
hashable type. The object supports both integer and label-based indexing and provides a host of
methods for performing operations involving the index.
Pandas Data Structures
Creating a Pandas Series

 In the real world, a Pandas Series will be created by loading the datasets from existing storage,
storage can be SQL Database, CSV file, and Excel file. Pandas Series can be created from the lists,
dictionaries, and from a scalar value, etc. Series can be created in different ways, here are some
ways by which we create a series:

 Creating a series from the array: In order to create a series from the array, we have to import a
numpy module and have to use the array() function.
Creating a Pandas Series

 .
Accessing element of Series

 .
Python Pandas DataFrame
. Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data
structure with labeled axes (rows and columns). A Data frame is a two-dimensional data structure, i.e.,
data is aligned in a tabular fashion in rows and columns. Pandas Data Frame consists of three principal
components, the data, rows, and columns
Creating a Pandas DataFrame
Creating DataFrame from dict of ndarray/lists:
Dealing with rows and column

 A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows
and columns. We can perform basic operations on rows/columns like selecting, deleting, adding,
and renaming.
 Column Selection: In Order to select a column in Pandas DataFrame, we can either access the
columns by calling them by their column name.
• Row Selection: Pandas provide a unique method to retrieve rows from a Data frame.
DataFrame.loc[] method is used to retrieve rows from Pandas DataFrame. Rows can also be selected
by passing integer location to an iloc[] function
Dealing with column
Dealing with rows
Dealing with rows
Dealing with rows and column

 A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows
and columns. We can perform basic operations on rows/columns like selecting, deleting, adding,
and renaming.
 Column Selection: In Order to select a column in Pandas DataFrame, we can either access the
columns by calling them by their columns name.
• Row Selection: Pandas provide a unique method to retrieve rows from a Data frame.
DataFrame.loc[] method is used to retrieve rows from Pandas DataFrame. Rows can also be selected
by passing integer location to an iloc[] function
List of Important Pandas Functions

FUNCTION DISCRIPTION

Pandas read_csv() Function This function is used to retrieve data from CSV files in the form of a dataframe

Pandas head() Function This function is used to return the top n (5 by default) values of a data frame
or series

This method is used to return the bottom n (5 by default) rows of a data frame
Pandas tail() Function
or series

This method is used to generate a sample random row or column from the
Pandas sample() Function
data frame.

This method is used to generate the summary of the DataFrame, this will
Pandas info() Function include info about columns with their names, their datatypes, and missing
values

Pandas dtypes() Function This method returns a Series with the data type of each colum
List of Important Pandas Functions

FUNCTION DISCRIPTION

It returns a tuple representing the dimensionality of the Pandas


Pandas shape() Function
DataFrame.

This method returns the number of rows in the Series. Otherwise, return
Pandas size() Function
the number of rows times the number of columns in the DataFrame.

Pandas ndim() Function This function returns 1 if Series and 2 if DataFrame

Pandas describe() Returns descriptive statistics about the data like mean, minimum,
Function maximum, standard deviation, etc.

Pandas unique() Function It returns all the unique values in a particular column.

Pandas nunique()
Returns the number of unique values in the column
Function
List of Important Pandas Functions

FUNCTION DISCRIPTION

Returns the DataFrame/Series of the boolean values. Missing values gets mapped
Pandas isnull() Function
to True and non-missing value gets mapped to False.

Python isna() Function Returns dataframe/series with bool values. Missing values gets mapped to True
and non-missing gets mapped to False.

Pandas fillna() Function This function is used to trim values at a specified input threshold.

Pandas clip() Function Returns index information of the DataFrame.

Pandas columns() Function Returns column names of the dataframe

Pandas sort_values()
This method sorts the data frame in ascending or descending order of passed
Function
Column
THESE TOPIC ALREADY COVERED IN UNIT1

What is python? How python in interpreted? What are the tools that helps to find the bugs or perform
static analysis?

What is python IDE? Discuss some python IDE?

Programming cycle in python

Elements of python type conversion

Operator precedence and Boolean expression

How memory is managed in python? Explain PEP8


How can you create a python file that can be imported as library as
well as run as a standalone script

 Module/ library are units that store code and data.


 It provided code reuse to python projects, and also useful in partitioning the system’s namespace in self-
contained packages
 They are self-contained because we can only access attributes of a module/library after importing it.
 Steps for importing python file as a library:
Step 1: create a file and name it test.py
Step 2: inside test.py create a function called display message().
For example
Def display_message(name):
return(“welcome”+name +”hello”)
How can you create a python file that can be imported as library as
well as run as a standalone script
Step 3: now create another file display.py
Step 4: inside display .py import the module test.py file as shown below :
Import test
While importing we do not have to mention the test.py but just the name of the file
Step 5: then we can call the function display _message () from test.py inside displau.py, we need to make use of module
_name, function.name
For example
Import test
Print(test.display_message(“Aditya))
Step6
When we execute display.py we will get the following output
Welcome Aditya hello
FUNCTION

 Python Functions is a block of statements that return the specific task. The idea is to put some
commonly or repeatedly done tasks together and make a function so that instead of writing the same
code again and again for different inputs, we can do the function calls to reuse code contained in it
over and over again.
 Some Benefits of Using Functions
 Increase Code Readability
 Increase Code Reusability
Types of Functions in Python
There are mainly two types of functions in Python
 Built-in library function: These are Standard functions in Python that are available to use.
 User-defined function: We can create our own functions based on our requirements.
Python Function Declaration
Python Function

 Syntax of function definition :


 def function name( arg 1, arg 2):
{
…..
}
Syntax of function call
Function_name( arg1,arg2)
Python Function

 Keyword: the keyword ‘def’ is used to define function header.


 Function name: we define the function name for identification or to uniquely identify the function.
 ( : ) a colon to mark the end of function header.
 Arguments these are the values passed to the function between parentheses
 Body of the function: the body process the argument to do something use ful
 An optional return statement to return the value from the function.
 function call To execute a function , we have to call it
Creating a Function in Python

 We can define a function in Python, using the def keyword. We can add any type of functionalities and
properties to it as we require.
Python Function with Parameters

 If you have experience in C/C++ or Java then you must be thinking about the return type of
the function and data type of arguments. That is possible in Python as well (specifically for
Python 3.5 and above).
 Defining and calling a function with parameters
 def function_name(parameter: data_type) -> return_type:
 """Docstring"""
 # body of the function
 return expression.
Python Function with Parameters
Types of Python Function Arguments

 Python supports various types of arguments that can be passed at the time of the function
call. In Python, we have the following 4 types of function arguments.
 Default argument
 Keyword arguments (named arguments)
 Positional arguments
 Arbitrary arguments (variable-length arguments *args and **kwargs)
Default Arguments

 A default argument is a parameter that assumes a default value if a value is not provided in the
function call for that argument
Keyword Arguments

 The idea is to allow the caller to specify the argument name with values so that the caller does not
need to remember the order of parameters.
Keyword Arguments

 Keyword-only arguments mean whenever we pass the arguments(or value) by their


parameter names at the time of calling the function in Python in which if you change the
position of arguments then there will be no change in the output.
 Benefits of using Keyword arguments over positional arguments
 On using keyword arguments you will get the correct output because the order of argument
doesn’t matter provided the logic of your code is correct. But in the case of positional
arguments, you will get more than one output on changing the order of the arguments..
Positional Arguments

 Position-only arguments mean whenever we pass the arguments in the order we have defined function
parameters in which if you change the argument position then you may get the unexpected output. We
should use positional Arguments whenever we know the order of argument to be passed.
 So now, we will call the function by using the position-only arguments in two ways, and In both cases,
we will be getting different outputs from which one will be correct and another one will be incorrect

 We used the Position argument during the function call so that the first argument (or value) is assigned
to name and the second argument (or value) is assigned to age. By changing the position, or if you
forget the order of the positions, the values can be used in the wrong places, as shown in the Case-2
example below, where 27 is assigned to the name and Suraj is assigned to the age
Positional Arguments
Arbitrary Keyword Arguments

 In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number of
arguments to a function using special symbols. There are two special symbols:
 *args in Python (Non-Keyword Arguments)
 **kwargs in Python (Keyword Arguments)
*args in Python (Non-Keyword Arguments)

 We can declare a variable length length argument with the*symbol


 The *args allows a function to accept any number of positional arguments
 The arguments are collected as a tuple within the function
*args in Python (Non-Keyword Arguments)
***kwargs in Python (Keyword Arguments)

 The *kwargs parameter allows a function to accept any number of keyword arguments.
 The arguments are collected as a dictionary within the function
Calculator using function
Calculator using function
Calculator using function
Python Scope variable

 The location where we can find a variable and also access it if required is called the scope of a variable
 Python Local variable
 Local variables are those that are initialized within a function and are unique to that function. It
cannot be accessed outside of the function
Python Scope variable

 Python Local variable


 If we will try to use this local variable outside the function
Python Scope variable
 Python Global variables
 Global variables are the ones that are defined and declared outside any function and are not
specified to any function. They can be used by any part of the program.
 Write a program factor(N) THAT RETURNS ALIST OF ALL POSITIVE DIVISOR OF N(N>=1)
 EXAMPLE FACTOR(6) RETURN [1,2,3,6]
 Write a python function remvekth(s,k) that take s as a input string and a n integer k>=0
and removes the character at a index k. if k is beyond the length of s , the whole os string
is returned
 removekth(“PYTHON”,1) return PTHON
 removekth(“PYTHON”,3) return PYTON
 removekth(“PYTHON”,20) return PYTHON
 Write a python code to find out occurrence of an elements in a list
Ques Write a python function, search Many(s,x,k) that takes an argument a sequence s and
integersx,k(k>0) the function returns true if there are at most k occurrences of x in s .otherwise it
returns false
 searching([10,17,15,12],15,1) return true, searching([10,12,12,12],12,2) return false
Python GUI – tkinter

 Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI
methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk
GUI toolkit shipped with Python. Python tkinter is the fastest and easiest way to create GUI
applications. Creating a GUI using tkinter is an easy task.
 To create a tkinter Python app:
 Importing the module – tkinter
 Create the main window (container)
 Add any number of widgets to the main window
 Apply the event Trigger on the widgets
Python GUI – tkinter

 Importing a tkinter is the same as importing any other module in the Python code. Note that the
name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’.
 import tkinter
 There are two main methods used which the user needs to remember while creating the Python
application with GUI.
Python GUI – tkinter

 There are two main methods used which the user needs to remember while creating the Python
application with GUI.
 Tk(screenName=None, baseName=None, className=’Tk’, useTk=1): To create a main window,
tkinter offers a method ‘Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)’. To
change the name of the window, you can change the class name to the desired one. The basic code
used to create the main window of the application is:
 m=tkinter.Tk() where m is the name of the main window object

 Main loop (): There is a method known by the name main loop () that is used when your application is
ready to run. Main loop () is an infinite loop used to run the application, wait for an event to occur,
and process the event as long as the window is not closed.
 m.mainloop()
Python GUI – tkinter

Tkinter also offers access to the geometric configuration of the widgets which can organize the widgets
in the parent windows. There are mainly three geometry manager classes class.
pack() method:It organizes the widgets in blocks before placing in the parent widget.
grid() method:It organizes the widgets in grid (table-like structure) before placing in the parent widget.
place() method:It organizes the widgets by placing them on specific positions directed by the
programmer.
Button:

 w=Button(master, option=value)
 master is the parameter used to represent the parent window. Several options are used to change
the format of the Buttons. Several options can be passed as parameters separated by commas.
Some of them are listed below
 active background: to set the background color when the button is under the cursor.
 Active foreground: to set the foreground color when the button is under the cursor.
 bg: to set the normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the button.
 width: to set the width of the button.
 height: to set the height of the button
Button:
Canvas

 It is used to draw pictures and other complex layout like graphics, text, and widgets. The general syntax is:
 w = Canvas(master, option=value)
 master is the parameter used to represent the parent window.
 There are a number of options that are used to change the format of the widget. A number of options can be
passed as parameters separated by commas. Some of them are listed below.
 bd: to set the border width in pixels.
 bg: to set the normal background color.
 cursor: to set the cursor used in the canvas.
 Highlight color: to set the color shown in the focus highlight.
 width: to set the width of the widget.
 height: to set the height of the wedge
Canvas
Check Button
 Select any number of options by displaying several options to a user as toggle buttons. The general
syntax is:
 w = Check Button(master, option=value)
 Several options are used to change the format of this widget. Several options can be passed as
parameters separated by commas. Some of them are listed below.
 Title: To set the title of the widget.
 Active background: to set the background color when widget is under the cursor.
 Active foreground: to set the foreground color when widget is under the cursor.
 bg: to set the normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the widget.
Check Button
Entry
 It is used to input the single-line text entry from the user. For multi-line text input, a Text widget is
used. The general syntax is:
 w=Entry(master, option=value)
 master is the parameter used to represent the parent window. Several options are used to change the
format of the widget. Several options can be passed as parameters separated by commas. Some of
them are listed below.
 bd: to set the border width in pixels.
 bg: to set the normal background color.
 cursor: to set the cursor used.
 command: to call a function.
 Highlight color: to set the color shown in the focus highlight.
 width: to set the width of the button.
 height: to set the height of the button..
Entry
AKTU Full Courses (Paid)
Download Gateway Classes Application
From Google Play store
All Subjects

Link in Description

You might also like