Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

python notebook

Python is a widely used, beginner-friendly programming language known for its simplicity and extensive libraries. It supports multiple programming paradigms and is utilized in various fields such as web development, data science, and artificial intelligence. Key features include dynamic typing, automatic memory management, and a strong community support.

Uploaded by

yinka
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

python notebook

Python is a widely used, beginner-friendly programming language known for its simplicity and extensive libraries. It supports multiple programming paradigms and is utilized in various fields such as web development, data science, and artificial intelligence. Key features include dynamic typing, automatic memory management, and a strong community support.

Uploaded by

yinka
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Python Programming Language

Python is one of the most popular and widely used programming language in nowadays, because
of its simplicity, extensive features and support of libraries. Python also have clean and simple
syntax which makes it beginner-friendly, while it also provides powerful libraries and
frameworks that makes it perfect for the developers.

What is Python?

Python is a general-purpose, dynamically typed, high-level, compiled and interpreted, garbage-


collected, and purely object-oriented programming language that supports procedural, object-
oriented, and functional programming.

Simple Python Program

print("Hello World!")

In Python, it is one line of code. It requires simple syntax to print 'Hello World'

Why Should You Learn Python?

Python provides many useful features to the programmer. These features make it the most
popular and widely used language. We have listed below few-essential features of Python.

I. Ease to use and Learn: Python has a simple and easy-to-understand syntax, unlike other
languages such as C, C++, Java, etc., which makes it easier for the beginners to learn.

II. Object-Oriented Language: It supports object-oriented programming, making writing


reusable and modular code easy.

III. GUI Programming Support: Python provides several GUI frameworks, such as Tkinter
and PyQt, which allows developers to create desktop application easily.

IV. Dynamic Memory Allocation: Python automatically manages memory allocation which
makes it easier for developers to write complex programs without worrying about
memory management.

V. Wide Range of Libraries and Frameworks: Python has a vast collection of libraries and
frameworks, such as NumPy, Pandas, Django, and Flask, that can be used to solve a wide
range of problems.

VI. Versatility: Python is a universal language in various domains such as web development,
machine learning, data analysis, scientific computing, and more.

Where is Python Used?

1
Python is a general-purpose, popular programming language, and it is used in almost every
technical field. The various areas of Python use are given below.

 Data Science: Data Science is a vast field, and Python is an important language for this
field because of its simplicity, ease of use, and availability of powerful data analysis and
visualization libraries like NumPy, Pandas, and Matplotlib.

 Artificial Intelligence: AI is an emerging Technology, and python is a perfect language


for the artificial intelligence and machine learning because of the availability of powerful
libraries such as TensorFlow, Keras, and Pytorch.

 Machine Learning: Python is also widely used for machine learning because of its
simplicity, ease of use and the availability of powerful machine learning libraries.

 Data Analysis: Python is also used to create visualizations of data. It is also used to
analyze the price trends and market predictions and automate workflows across multiple
data sources.

 Web Development: Python is used to develop websites and web applications. There are
several popular frameworks like Django and Flask which are used to build web
applications.

Python Popular Frameworks and Libraries

Python has wide range of libraries and frameworks widely used in various fields such as machine
learning, artificial intelligence, web applications, etc. We define some popular frameworks and
libraries of Python as follows.

Web development (Server-side) - Django Flask, Pyramid, CherryPy

GUIs based applications - Tkinter, PyGTK, PyQt, PyJs, etc.

Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.

Mathematics - NumPy, Pandas, etc.

BeautifulSoup: a library for web scraping and parsing HTML and XML

Requests: a library for making HTTP requests

SQLAlchemy: a library for working with SQL databases

Kivy: a framework for building multi-touch applications

Pygame: a library for game development

2
Pytest: a testing framework for Python Django

REST framework: a toolkit for building RESTful APIs

FastAPI: a modern, fast web framework for building APIs

Streamlit: a library for building interactive web apps for machine learning and data science

NLTK: a library for natural language processing

Features of Python

From the development of Ada Lovelace's machine algorithm in 1843 to the latest and popular
high-level programming languages like C++, Python, and Java, a wide range of programming
languages have been developed by programmers in order to solve real-world challenging
problems. However, not every programming language stands out in the limelight. Every
programming language is dependent on their core features like accessibility, flexibility,
portability, responsibility, and a lot more. In simpler terms, the utility of any programming
language is considered using its essential features.

1. Free and Open Source

Python is a programming language freely available at the official website. One can download
and install it by clicking on the following link: Download Python. Python, being an open-source
programming language, allows users to access its source code available to the public. This source
code can be downloaded for usage as well as sharing purpose allowing users to contribute to the
Python community from around the world.

2. Easy to Learn and Code: Python is a high-level programming language that is quite easier to
learn when compared to other programming languages like C, Java, C#, JavaScript, etc. Python
offers a clean and simple syntax, similar to plain English making it easy for beginners to
comprehend and write programs quickly.

Let us consider the following example.

Example

print("Hello, World! Welcome to Tpoint Tech.")

Output:

Hello, World! Welcome to Tpoint Tech.

In the above example, we can observe that a simple line of code prints a message on the screen.

3
3. Easy to Read: Python is an expressive language with quite straightforward syntax. The chunks
of code in Python are structured using the indentations making it exceptional programming
language when compared to other programming languages like C++ or Java.

4. Object-Oriented Language: Python offers support for the object-oriented paradigm, a


programming approach where software system is designed and developed with the help of
"objects", which are basically blueprints (known as classes) that define data (known as attributes)
and behaviors (known as methods) allowing developers to organize code in a well-structured
format. To understand the concept of object-oriented programming (OOP), let us consider an
example of a Car. A Car can be treated as an object where its color, brand, model, variant, price,
etc., would be its properties and acceleration, brake, and gear change would be its behaviors /or
functions. OOP supports various concepts like abstraction, inheritance, polymorphism,
encapsulation, and more, allowing users to write reusable code and develop applications
efficiently and effectively.

5. Cross-Platform Compatibility: Python is also a portable language that can be run on different
operating systems (like Windows, MacOS, Linux, Unix) without any modification. This feature
of Python allows programmers to write and run any of its scripts on any platform without the
need to change anything.

6. Interpreted Language: Python is an interpreted language as it runs code line by line, rather
than compiling the complete code into machine code before execution. At first, Python
interpreter reads the Python source code and converts it into an immediate form called bytecode.
This bytecode is then executed by the Python virtual machine. This process makes debugging
much easier as the errors are detected quickly.

7. Dynamically Typed Language: Python is also a dynamically typed language allowing Python
to figure out the variable types (int, double, long, etc.) automatically at the run time, without the
need of declaring them manually.

Let us consider the following example:

Example

# initializing some variables

var_1 = 5

var_2 = 4.7

var_3 = "Welcome"

# printing the results

print("Value of var_1:", var_1)

4
print("Value of var_2:", var_2)

print("Value of var_3:", var_3)

Output:

Value of var_1: 5

Value of var_2: 4.7

Value of var_3: Welcome

Explanation:

In the above snippet of code, we have defined three different variables without declaring their
types. We have then printed their values along with their types. As a result, we can observe that
their types have been assigned automatically and correctly by Python itself.

8. High-Level Language: Python is a high-level language. This feature allows programmers to


mainly focus on solving problems rather than dealing with the hardware details like system
architecture or memory allocation.

9. Integrated Language: Python is an integrated language because it can be readily connected


with other programming languages like C, C++, Java, and more. This feature allows
programmers to use existing libraries of Python in other language. Being an integrated language,
Python also provides a comprehensive set of features and utilities in order to support different
aspects of software development.

10. GUI Programming Support: Python also provides an excellent support for the development
of Graphical User Interfaces (GUIs) through various libraries and frameworks.

11. Multipurpose Programming: Python is a multi-purpose programming language that can be


used for a wide range of applications, including web development, data analysis, automation,
machine learning, and scientific computing. This makes it versatile for various types of projects
due to its simple syntax and extensive libraries.

Python plays a significant role in web development. With the use of simple tags like <py-script>,
<py-env>, etc., can be used to write and run Python codes in HTML, allowing programmers to
do front-end development work in Python with JavaScript. Python provides multiple frameworks
like Django and Flask to do back-end development.

12. Strong Community Support: Python has gained popularity over the year making it one of the
most favourable programming languages for multi-purpose development. This leads Python to
have a huge community around the world. There are multiple forums, documentations, and

5
tutorials available online in order to help user to learn and resolve any problems while
programming.

13. Extensive Libraries and Frameworks: Python has a huge collection of libraries and
frameworks, making development faster, easier and more efficient across different domains. This
feature of Python allows developers to mainly focus on solving problems and save their time
from writing everything from scratch.

14. Multiple Programming Paradigms Support: Python is a programming language that supports
multiple programming paradigms, which makes it a highly versatile and powerful language

15. Automatic Memory Management: Python offers automatic memory management, which
means developers do not require to allocate or deallocate memory manually. The memory
manager of Python handles object creation, memory allocation, garbage collection, and memory
optimization automatically. Let us take an example where we can see Python's automatic
memory management in act. Suppose that we have a Python program that manages user
accounts. Each time a user logs in, an object is created, and when they log out, the object is
automatically removed.

16. Multi-threading and Multiprocessing: Python allows multiple tasks to run at once. This
process is known as concurrency, and it can be achieved by the multi-threading and
multiprocessing features of Python.

Python Applications

1) Web Applications: We can use Python to develop web applications. It provides libraries to
handle internet protocols such as HTML and XML, JSON, Email processing, request,
beautifulSoup, Feedparser, etc. One of Python web-framework named Django is used on
Instagram. Python provides many useful frameworks, and these are given below:

Django and Pyramid framework(Use for heavy applications)

Flask and Bottle (Micro-framework)

Plone and Django CMS (Advance Content management)

2) Desktop GUI Applications: The GUI stands for the Graphical User Interface, which provides
a smooth interaction to any application. Python provides a Tk GUI library to develop a user
interface. Some popular GUI libraries are given below.

Tkinter or Tk

wxWidgetM

Kivy (used for writing multitouch applications )

6
PyQt or Pyside

3) Console-based Application: Console-based applications run from the command-line or shell.


These applications are computer program which are used commands to execute. This kind of
application was more popular in the old generation of computers. Python can develop this kind
of application very effectively. It is famous for having REPL, which means the Read-Eval-Print
Loop that makes it the most suitable language for the command-line applications. Python
provides many free library or module which helps to build the command-line apps. The
necessary IO libraries are used to read and write. It helps to parse argument and create console
help text out-of-the-box. There are also advance libraries that can develop independent console
apps.

4) Software Development: Python is useful for the software development process. It works as a
support language and can be used to build control and management, testing, etc.

SCons is used to build control.

Buildbot and Apache Gumps are used for automated continuous compilation and testing.

Round or Trac for bug tracking and project management.

5) Scientific and Numeric: This is the era of Artificial intelligence where the machine can
perform the task the same as the human. Python language is the most suitable language for
Artificial intelligence or machine learning. It consists of many scientific and mathematical
libraries, which makes easy to solve complex calculations.

Implementing machine learning algorithms require complex mathematical calculation. Python


has many libraries for scientific and numeric such as Numpy, Pandas, Scipy, Scikit-learn, etc. If
you have some basic knowledge of Python, you need to import libraries on the top of the code.
Few popular frameworks of machine libraries are given below.

SciPy

Scikit-learn

NumPy

Pandas

Matplotlib

6) Business Applications: Business Applications differ from standard applications. E-commerce


and ERP are an example of a business application. This kind of application requires extensively,
scalability and readability, and Python provides all these features.

7
Oddo is an example of the all-in-one Python-based application which offers a range of business
applications. Python provides a Tryton platform which is used to develop the business
application.

7) Audio or Video-based Applications: Python is flexible to perform multiple tasks and can be
used to create multimedia applications. Some multimedia applications which are made by using
Python are TimPlayer, cplay, etc. The few multimedia libraries are given below.

Gstreamer

Pyglet

QT Phonon

8) 3D CAD Applications: The CAD (Computer-aided design) is used to design engineering


related architecture. It is used to develop the 3D representation of a part of a system. Python can
create a 3D CAD application by using the following functionalities.

Fandango (Popular )

CAMVOX

9) Enterprise Applications: Python can be used to create applications that can be used within an
Enterprise or an Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.

10) Image Processing Application: Python contains many libraries that are used to work with the
image. The image can be manipulated according to our requirements. Some libraries of image
processing are given below.

OpenCV

Pillow

SimpleITK

Hello World Program in Python

With the rapid growth of Python in new technologies, it continues to define the future of
software development, which makes it an important skill in today's tech environment.

our first Python program.

Python Program to Print - Hello, World!

Let us start our journey with Python using a classic introductory program in almost every
programming language. It simply prints the text "Hello, World!" on the console.

8
Example

# simple "Hello, World!" program in Python

# using the print() function to print the text "Hello, World!"

print("Hello, World!")

Output:

Hello, World!

Explanation:

In the above snippet of code, we have used print(), a built-in function in Python, to display
output to the user. "Hello, World!" is a string literal. It's the text we want to display, enclosed
within double quotes. The print() function takes this string as input and displays it.

Things to Remember While Working with Python:

Indentation: Python uses indentation in order to define code blocks. Unlike other programming
languages that make use of parentheses {} or keywords, Python uses proper indentation in the
form of spaces or tabs for the code to function correctly. Moreover, it also improves the
readability of the code.

Dynamic Typing: Python is dynamically typed language. This means that we are not required to
declare the data types of variables explicitly. For example, x = 10 is an integer, but assigning x =
"hello" later changes it to a string.

Virtual Environments: Python supports virtual environments (venv) which helps isolating the
dependencies for different projects. This also helps preventing package conflicts and ensuring
each project runs with the required library versions.

Extensive Library Support: Python offers a rich set of built-in libraries like math, itertools,
datetime, collections, and functools, enabling efficient problem-solving without reinventing the
wheel.

PEP 8: Python's official style guide promotes best practices such as meaningful variable names,
consistent indentation, proper spacing, and a 79-character line limit for better code readability
and maintainability.

Simple programs in Python.

Example 1: Printing Your Name

Example

9
# simple program to print your name in Python

# initializing a variable to store name

name = "Eren"

# using the print() function to display the name

print("Name =>", name)

Output:

Name => Eren

Explanation:

In the above example, we have defined a variable as name and initialized it with a value - "Eren".
We have then used the print() function to display the name for the users.

Example 2: Addition of Two Numbers

Example

# simple program to add two numbers in Python

# initializing variables

num_1 = 24

num_2 = 31

# adding the variables and storing their result

sum = num_1 + num_2

# printing the result

print(f"{num_1} + {num_2} = {sum}")

Output:

24 + 31 = 55

Explanation:

In the above program, we have defined two variables as num_1 and num_2, and initialized them
with the values - 24 and 31, respectively. We have then performed addition of these two
variables and stored their result in a third variable called sum. Finally, we have used the print()
function to display the output to the users.

10
Example 3: Taking Input from the Users

Example

# simple program to take input from user in Python

# using the input() function to take input from the user

user_input = input("Enter Your Text: ")

# printing the input text

print("Entered Text:", user_input)

Output:

Enter Your Text: Learning Python with Tpoint Tech is Easy!

Entered Text: Learning Python with Tpoint Tech is Easy!

Explanation:

In the above example, we have used the input() function. input() is a built-in function in Python
that waits for the user to type something and press Enter. We have added a prompt "Enter Your
Text: " in the input() function that is displayed to users, guiding them what to enter. We have
defined a variable as user_input to store the entered value from the user. We have then used the
print() function to display the entered text from the user..

Python Keywords

Every scripting language has designated words or keywords, with particular definitions and
usage guidelines. Python is no exception. The fundamental constituent elements of any Python
program are Python keywords.

Introducing Python Keywords

Python keywords are unique words reserved with defined meanings and functions that we can
only apply for those functions. You'll never need to import any keyword into your program
because they're permanently present.

Python's built-in methods and classes are not the same as the keywords. Built-in methods and
classes are constantly present; however, they are not as limited in their application as keywords.

Assigning a particular meaning to Python keywords means you can't use them for other purposes
in our code. You'll get a message of SyntaxError if you attempt to do the same. If you attempt to
assign anything to a built-in method or type, you will not receive a SyntaxError message;
however, it is still not a smart idea.

11
Python contains thirty-five keywords in the most recent version, i.e., Python 3.8. Here we have
shown a complete list of Python keywords for the reader's reference.

False

await

else

import

pass

None

break

except

in

raise

True

Class e.t.c

Introduction to Python Comments

We may wish to describe the code we develop. We might wish to take notes of why a section of
script functions, for instance. We leverage the remarks to accomplish this. Formulas, procedures,
and sophisticated business logic are typically explained with comments. The Python interpreter
overlooks the remarks and solely interprets the script when running a program. Single-line
comments, multi-line comments, and documentation strings are the 3 types of comments in
Python.

Advantages of Using Comments

Our code is more comprehensible when we use comments in it. It assists us in recalling why
specific sections of code were created by making the program more understandable.

Aside from that, we can leverage comments to overlook specific code while evaluating other
code sections. This simple technique stops some lines from running or creates a fast pseudo-code
for the program.

Below are some of the most common uses for comments:

12
 Readability of the Code

 Restrict code execution

 Provide an overview of the program or project metadata

 To add resources to the code

Types of Comments in Python

In Python, there are 3 types of comments. They are described below:

 Single-Line Comments: Single-line remarks in Python have shown to be effective for


providing quick descriptions for parameters, function definitions, and expressions. A single-
line comment of Python is the one that has a hashtag # at the beginning of it and continues
until the finish of the line. If the comment continues to the next line, add a hashtag to the
subsequent line and resume the conversation. Consider the accompanying code snippet,
which shows how to use a single line comment:

Code

# This code is to show an example of a single-line comment

print( 'This statement does not have a hashtag before it' )

Output:

This statement does not have a hashtag before it

The following is the comment:

# This code is to show an example of a single-line comment

The Python compiler ignores this line.

Everything following the # is omitted. As a result, we may put the program mentioned above in
one line as follows:

Code

print( 'This is not a comment' ) # this code is to show an example of a single-line comment

Output:

This is not a comment

This program's output will be identical to the example above. The computer overlooks all content
following #.

13
 Multi-Line Comments

Python does not provide the facility for multi-line comments. However, there are indeed many
ways to create multi-line comments.

With Multiple Hashtags (#)

In Python, we may use hashtags (#) multiple times to construct multiple lines of comments.
Every line with a (#) before it will be regarded as a single-line comment.

Code

# it is a

# comment

# extending to multiple lines

In this case, each line is considered a comment, and they are all omitted.

Using String Literals

Because Python overlooks string expressions that aren't allocated to a variable, we can utilize
them as comments.

Code

'it is a comment extending to multiple lines'

We can observe that on running this code, there will be no output; thus, we utilize the strings
inside triple quotes(""") as multi-line comments.

 Python Docstring

The strings enclosed in triple quotes that come immediately after the defined function are called
Python docstring. It's designed to link documentation developed for Python modules, methods,
classes, and functions together. It's placed just beneath the function, module, or class to explain
what they perform. The docstring is then readily accessible in Python using the __doc__
attribute.

Code

# Code to show how we use docstrings in Python

def add(x, y):

"""This function adds the values of x and y"""

14
return x + y

# Displaying the docstring of the add function

print( add.__doc__ )

Output:

This function adds the values of x and y

Python Variables

In Python, variables are essentially constructing blocks that allow developers to store, control,
and manage data efficaciously. A variable in Python is largely a symbolic name assigned to a
memory place in which data is stored. Unlike statically typed languages (together with C or
Java), Python is dynamically typed, which means variables no longer require specific
announcements of their type; the type is inferred at runtime primarily based on the assigned fee.

Why Are Variables Important?

 Variables offer a way to save and manage information.

 They allow reusability, decreasing redundancy in code.

 They make it less difficult to alter, debug, and maintain code.

 They facilitate dynamic memory allocation in Python.

Key Features of Variables in Python

Python variables have several specific functions that make them incredibly easy and smooth to
use. Let's discover those key functions in detail.

1. No Need for Explicit Type Declaration: Python is not a strict language like C or Java, one
need not define a variable before using it, like we do in Java or C language. One need not define
the type of variable. It directly defines the type of variable based on the value that the users store
in it during the execution.

Example:

x = 10 # Integer

y = 3.14 # Float

name = "John" # String

is_active = True # Boolean

15
Here, Python automatically detects x as an integer, y as a float, name as a string, and is_active as
a Boolean with no explicit type declaration.

2. Dynamically Typed: Python is a dynamically types language which indicates that one can
change the type of variable during the runtime also. One can change the variable types during the
execution without any problems or errors.

Example:

x = 1000 # Initially an integer

print(type(x)) # Output: <class 'int'>

x = "Python" # Now changed to a string

print(type(x)) # Output: <class 'str'>

This flexibility helps Python developers to write concise and adaptable code. However, it also
calls for cautious management to keep away from accidental errors.

3. Memory Efficient (Variables Reference Objects, Not Raw Data): In Python, variables do not
store values directly. Instead, they act as references (or pointers) to objects in memory. When a
variable is assigned a value, it references an object in Python's memory space rather than storing
the actual raw data.

Example:

a = 10

b = a # 'b' also refers to the same object as 'a'

print(id(a), id(b)) # Both variables reference the same memory location

If two unchangeable values are stored in two variable like numbers, strings or tuples, then python
will optimize the memory utilization of variable without duplicating the information and pointing
each variable to same object.

4. Easy Reassignment (Variables Can Hold Different Types): Python variables are not fixed to a
single data type. They can be reassigned to different types at any point during program
execution.

Example:

x = 42 # x is an integer

x = "Hello" # x is now a string

16
x = [1, 2, 3] # x is now a list

Advantage:

This makes Python enormously flexible for fast improvement and prototyping.

Disadvantage:

This can cause unexpected errors so that type checking can be needed.

5. Used for Storing Values, Objects, and Complex Data Structures: The language Python is store
variable from simple data type like strings and integers to more complex data types like lists,
dictionaries, sets and many more user defined objects.

Examples of Data Types Stored in Variables

num = 100 # Integer

a = 2.34566 # Float

message = "Hello, Goutham!" # String

fruits = ["Alex", "Ana"] # List

person = {"name": "Alex", "age": 21} # Dictionary

coordinates = (10, 20) # Tuple

is_valid = True # Boolean

This feature made python to be used in many advanced technologies like data science, web
development, machine learning and many more.

Declaring and Assigning Variables in Python

Variable Declaration: In python, one need not define the variable at the beginning before storing
a value in it like they do in other programming languages. Simply using the assignment operator
(=) is sufficient.

Syntax:

variable_name = value

Example:

name = "Alice" # A string variable

age = 25 # An integer variable

17
height = 5.6 # A float variable

is_student = True # A boolean variable

Key Points:

Python automatically detects the data type based on the value assigned.

Certain naming conventions must be followed by Variable names (discussed later).

Variables can preserve distinct data types consisting of integers, floats, strings, lists, and more.

Rules and Naming Conventions for Python Variables

Python follows certain rules and best practices for naming variables:

Rules for Variable Naming:

 The names of the variables have to start with a letter (A-Z or a-z) or an underscore (_)

 The last characters may be letters, digits (0-9), or underscores (_)

 Variable names are case-sensitive (age and Age are different)

 Reserved Python keywords cannot be used as variable names (class, def, return, etc.)

Examples of Valid and Invalid Variables:

# Valid variable names

my_variable = 10

_name = "Alice"

variable_123 = 42

CamelCaseVariable = "Hello"

# Invalid variable names (these will cause errors)

123name = "John" # Cannot start with a number

my-variable = 5 # Cannot contain hyphens

if = 10 # Cannot use reserved keywords

Best Practice: Use meaningful variable names to enhance code readability.

Good: user_age, total_amount, first_name

18
Bad: x, a1, var1

Types of Variables in Python

Python supports multiple data types for variables. The type of a variable is automatically
determined when a value is assigned.

Common Variable Types and Examples

Data Type

 int

Integer values

x = 10

 float

Decimal values

y = 3.14

 str

Text (string)

name = "Alice"

 bool

Boolean values

is_active = True

Assigning Multiple Variables in Python: Python makes the code extra readable and efficient by
adding this feature of assigning more than one variable at once. Let's discover the multiple
methods to access more than one variable assigned in Python.

Example 1: Multiple Assignments (Tuple Unpacking)

Python allows assigning more than one variable in a single line via isolating them with commas.
This is frequently known as tuple unpacking, though parentheses are optionally available.

Syntax:

variable1, variable2, variable3 = v1, v2, v3

Example

19
a, b, c = 110, 120, 130

print(a, b, c) # Output: 110 120 130

Output:

10 20 30

Explanation:

In first line, the values 110, 120, and 130 are assigned to a, b, and c.

A gets 110, b gets 120, and c gets 130.

This approach improves readability and reduces redundant venture statements.

Advantages:

Saves time by reducing the number of assignment statements.

Makes the code more readable and easier.

Global and Local Variables in Python

In Python, it's very important to know the scope and lifetime of variables, in order to know them
one has to understand the concept of local and global variables. These variables differ in where
and how they are being accessed. Let's go deeper into the concepts and understand how exactly
these variables work.

1. Local Variables in Python: A local variable is defined inside a function and can be accessed
inside that function.

Once the characteristic execution ends, the local variable is destroyed and is now not handy.

Characteristics:

Scope: Limited to the function where it is defined.

Lifetime: Exists only during the function's execution.

Example

def my_function():

local_var = "I'm local"

print(local_var)

20
my_function()

# print(local_var) # Uncommenting this line will raise an error because local_var is not
accessible outside the function.

Output:

I'm local

Explanation:

local_var is defined inside the function my_function().

It is only accessible within the function.

When you attempt to print local_var outside the function, Python will boost a NameError
because local_var isn't always defined inside the global scope.

2. Global Variables in Python: A global variable is defined outside the function and can be
accessed with the aid of any part of this program.

Global variables can be used across distinctive functions, and their values persist at some stage in
the program execution.

Characteristics:

Scope: Available throughout the program, including inside functions.

Lifetime: Exists for the entire duration of the program.

Example

global_var = "I'm global" # Global variable

def display():

print(global_var) # Accessing the global variable

display() # Output: I'm global

Output:

I'm global

Explanation:

global_var is defined outside the function, making it a global variable.

21
The display() function can access and print the global variable global_var even though it is
defined outside the function.

This suggests that global variables are accessible globally across the program.

Variable Type Conversion (Type Casting) in Python

In Python, kind conversion (or kind casting) refers to the process of changing one data type into
another. Python helps with each implicit and explicit type of conversion, which allows flexibility
in dealing with variables of various types.

1. Implicit Type Conversion (Automatic Type Conversion): Implicit type conversion, also called
automatic kind conversion, occurs when Python automatically converts one data type to any
other without explicit instruction from the programmer. This happens when you perform
operations on compatible data types, and Python guarantees that the operation executes
smoothly.

How It Works:

Python automatically promotes smaller or much less specific types to large or more precise ones.

For instance, if you upload an int to a float, Python automatically converts the int to a float to
avoid data loss.

Example

a = 10 # int

b = 2.5 # float

c = a + b # float (implicit conversion)

print(c, type(c)) # Output: 12.5 <class 'float'>

Output:

12.5 <class 'float'>

Explanation:

Here, a is an (int), and b is a (float).

When a+b is done, Python will convert the integer data type "a" to a data type float so that the
addition will be done inside the float data type only.

As a result, the variable c holds a data type float value (12.5), and its type is <class 'float'>.

Key Points About Implicit Type Conversion:

22
Python best performs implicit conversions between compatible types (e.g., int to float, int to
complex).

Implicit conversion does not show up, but it can bring a loss of precision or data (e.g., converting
a float to an int automatically).

2. Explicit Type Conversion (Manual Type Conversion): Explicit type conversion, additionally
known as manual type casting, takes place when you use Python's built-in function to convert a
variable from one type to another. You must specify the type you want to convert a variable into.

Common Functions for Explicit Conversion:

int(): Converts any value to an integer.

float(): Converts any value to a floating-point number.

str(): Converts any value to a string.

list(): Converts any value (like a string or tuple) into a list.

Example 1: String to Integer Conversion

Example

x = "100" # string

y = int(x) # Converts string to integer

print(y, type(y)) # Output: 100 <class 'int'>

Output:

100 <class 'int'>

Explanation:

x is a string ("100"), as we wanted to perform mathematical operations with it, so we convert it


to an integer the use of the int() characteristic.

The string "100" is converted to the data type integer 100.

After conversion, y holds the integer value 100, and its type is <class 'int'>.

Special Variables (__name__ and __main__) in Python

1. __name__ Variable:

23
A special integrated variable that stores the name of the current module that the user is working
on, in python is _name_ variable. When one runs a Python file, the value of __name__ is set to
"__main__" , if the file is executed without any delay. If the file is imported as a module from
another script, __name__ is set to the module's name. This feature gives us a difference when
running a script without any delay and uploading the script as a part of another program.

2. __main__ Block:

A common Python idiom that is used commonly is The if __name__ == "__main__": block is
used to check whether the script is being run immediately (as opposed to imported). When the
script will be run without delay then only the code that is inside this block will be executed. This
will be useful for writing code that may function both as a standalone script and as a reusable
module.

Example:

if __name__ == "__main__":

print("This script is running directly.")

else:

print("This script has been imported.")

When run directly: "This script is running directly."

When imported: "This script has been imported."

Deleting Variables in Python

In Python, one can delete a variable using the del keyword. Once a variable is deleted, it gets
eliminated from the memory, and attempting to get access to it afterward will raise an error.

Example:

x = 100

del x

# print(x) # This would raise an error since x is deleted.

The variable x is assigned a value of 100, and then del x removes it from memory.

Trying to print x after deletion will raise a NameError because the variable no longer exists.

Python Data Types

24
Every value has a datatype, and variables can hold values. Python is a powerfully composed
language; consequently, we don't have to characterize the sort of variable while announcing it.
The interpreter binds the value implicitly to its type.

a=5

We did not specify the type of the variable a, which has the value five from an integer. The
Python interpreter will automatically interpret the variable as an integer.

We can verify the type of the program-used variable thanks to Python. The type() function in
Python returns the type of the passed variable.

Consider the following illustration when defining and verifying the values of various data types.

a=10

b="Hi Python"

c = 10.5

print(type(a))

print(type(b))

print(type(c))

Output:

<type 'int'>

<type 'str'>

<type 'float'>

Standard data types

A variable can contain a variety of values. On the other hand, a person's id must be stored as an
integer, while their name must be stored as a string. The storage method for each of the standard
data types that Python provides is specified by Python. The following is a list of the Python-
defined data types.

 Numbers

 Sequence Type

 Boolean

25
 Set

 Dictionary

Numbers: Numeric values are stored in numbers. The whole number, float, and complex
qualities have a place with a Python Numbers datatype. Python offers the type() function to
determine a variable's data type. The instance () capability is utilized to check whether an item
has a place with a specific class.

When a number is assigned to a variable, Python generates Number objects. For instance,

a=5

print("The type of a", type(a))

b = 40.5

print("The type of b", type(b))

c = 1+3j

print("The type of c", type(c))

print(" c is a complex number", isinstance(1+3j,complex))

Output:

The type of a <class 'int'>

The type of b <class 'float'>

The type of c <class 'complex'>

c is complex number: True

Python supports three kinds of numerical data.

 Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and so on.
An integer can be any length you want in Python. Its worth has a place with int.

 Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to
within 15 decimal places.

 Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y signify
the genuine and non-existent parts separately. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.

Sequence Type

26
String: The sequence of characters in the quotation marks can be used to describe the string. A
string can be defined in Python using single, double, or triple quotes. String dealing with Python
is a direct undertaking since Python gives worked-in capabilities and administrators to perform
tasks in the string. When dealing with strings, the operation "hello"+" python" returns "hello
python," and the operator + is used to combine two strings. Because the operation "Python" *2
returns "Python," the operator * is referred to as a repetition operator.

The Python string is demonstrated in the following example.

Example - 1

str = "string using double quotes"

print(str)

s = '''''A multiline

string'''

print(s)

Output:

string using double quotes

A multiline

string

Look at the following illustration of string handling.

Example - 2

str1 = 'hello javatpoint' #string str1

str2 = ' how are you' #string str2

print (str1[0:2]) #printing first two character using slice operator

print (str1[4]) #printing 4th character of the string

print (str1*2) #printing the string twice

print (str1 + str2) #printing the concatenation of str1 and str2

Output:

he

27
o

hello javatpointhello javatpoint

hello javatpoint how are you

List: Lists in Python are like arrays in C, but lists can contain data of different types. The things
put away in the rundown are isolated with a comma (,) and encased inside square sections []. To
gain access to the list's data, we can use slice [:] operators. Like how they worked with strings,
the list is handled by the concatenation operator (+) and the repetition operator (*).

Look at the following example.

Example:

list1 = [1, "hi", "Python", 2]

#Checking type of given list

print(type(list1))

#Printing the list1

print (list1)

# List slicing

print (list1[3:])

# List slicing

print (list1[0:2])

# List Concatenation using + operator

print (list1 + list1)

# List repetation using * operator

print (list1 * 3)

Output:

[1, 'hi', 'Python', 2]

[2]

[1, 'hi']

28
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

Tuple: In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items
from various data types. A parenthetical space () separates the tuple's components from one
another. Because we cannot alter the size or value of the items in a tuple, it is a read-only data
structure.

Let's look at a straightforward tuple in action.

Example:

tup = ("hi", "Python", 2)

# Checking type of tup

print (type(tup))

#Printing the tuple

print (tup)

# Tuple slicing

print (tup[1:])

print (tup[0:1])

# Tuple concatenation using + operator

print (tup + tup)

# Tuple repatation using * operator

print (tup * 3)

# Adding value to tup. It will throw an error.

t[2] = "hi"

Output:

<class 'tuple'>

('hi', 'Python', 2)

('Python', 2)

29
('hi',)

('hi', 'Python', 2, 'hi', 'Python', 2)

('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Traceback (most recent call last):

File "main.py", line 14, in <module>

t[2] = "hi";

TypeError: 'tuple' object does not support item assignment

Dictionary: A dictionary is a key-value pair set arranged in any order. It stores a specific value
for each key, like an associative array or a hash table. Value is any Python object, while the key
can hold any primitive data type.

The comma (,) and the curly braces are used to separate the items in the dictionary.

Look at the following example.

d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}

# Printing dictionary

print (d)

# Accesing value using keys

print("1st name is "+d[1])

print("2nd name is "+ d[4])

print (d.keys())

print (d.values())

Output:

1st name is Jimmy

2nd name is mike

{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}

dict_keys([1, 2, 3, 4])

30
dict_values(['Jimmy', 'Alex', 'john', 'mike'])

Boolean: True and False are the two default values for the Boolean type. These qualities are
utilized to decide the given assertion valid or misleading. The class book indicates this. False can
be represented by the 0 or the letter "F," while true can be represented by any value that is not
zero.

Look at the following example.

# Python program to check the boolean type

print(type(True))

print(type(False))

print(false)

Output:

<class 'bool'>

<class 'bool'>

NameError: name 'false' is not defined

Set: The data type's unordered collection is Python Set. It is iterable, mutable(can change after
creation), and has remarkable components. The elements of a set have no set order; It might
return the element's altered sequence. Either a sequence of elements is passed through the curly
braces and separated by a comma to create the set or the built-in function set() is used to create
the set. It can contain different kinds of values.

Look at the following example.

# Creating Empty set

set1 = set()

set2 = {'James', 2, 3,'Python'}

#Printing Set value

print(set2)

# Adding element to the set

set2.add(10)

print(set2)

31
#Removing element from the set

set2.remove(2)

print(set2)

Output:

{3, 'Python', 'James', 2}

{'Python', 'James', 3, 2, 10}

{'Python', 'James', 3, 10}

Python Control Structures

Python If-else statements:

Decision making is the most important aspect of almost all the programming languages. As the
name implies, decision making allows us to run a particular block of code for a particular
decision. Here, the decisions are made on the validity of the particular conditions. Condition
checking is the backbone of decision making.

In python, decision making is performed by the following statements.

If Statement: The if statement is used to test a specific condition. If the condition is true, a block
of code (if-block) will be executed.

If - else Statement: The if-else statement is similar to if statement except the fact that, it also
provides the block of the code for the false case of the condition to be checked. If the condition
provided in the if statement is false, then the else statement will be executed.

Nested if Statement: Nested if statements enable us to use if ? else statement inside an outer if
statement.

Indentation in Python

For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block. If two
statements are at the same indentation level, then they are the part of the same block.

Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python. Indentation is the most used part of the python language since it declares
the block of code. All the statements of one block are intended at the same level indentation. We
will see how the actual indentation takes place in decision making and other stuff in python.

32
The if statement The if statement is used to test a particular condition and if the condition is true,
it executes a block of code known as if-block. The condition of if statement can be any valid
logical expression which can be either evaluated to true or false.

Python If-else statements

The syntax of the if-statement is given below.

if expression:

statement

Example 1

# Simple Python program to understand the if statement

num = int(input("enter the number:"))

# Here, we are taking an integer num and taking input dynamically

if num%2 == 0:

# Here, we are checking the condition. If the condition is true, we will enter the block

print("The Given number is an even number")

Output:

enter the number: 10

The Given number is an even number

Example 2 : Program to print the largest of the three numbers.

# Simple Python Program to print the largest of the three numbers.

a = int (input("Enter a: "));

b = int (input("Enter b: "));

c = int (input("Enter c: "));

if a>b and a>c:

# Here, we are checking the condition. If the condition is true, we will enter the block

print ("From the above three numbers given a is largest");

if b>a and b>c:

33
# Here, we are checking the condition. If the condition is true, we will enter the block

print ("From the above three numbers given b is largest");

if c>a and c>b:

# Here, we are checking the condition. If the condition is true, we will enter the block

print ("From the above three numbers given c is largest");

Output:

Enter a: 100

Enter b: 120

Enter c: 130

From the above three numbers given c is largest

The if-else statement

The if-else statement provides an else block combined with the if statement which is executed in
the false case of the condition.

If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.

Python If-else statements

The syntax of the if-else statement is given below.

if condition:

#block of statements

else:

#another block of statements (else-block)

Example 1 : Program to check whether a person is eligible to vote or not.

# Simple Python Program to check whether a person is eligible to vote or not.

age = int (input("Enter your age: "))

# Here, we are taking an integer num and taking input dynamically

if age>=18:

34
# Here, we are checking the condition. If the condition is true, we will enter the block

print("You are eligible to vote !!");

else:

print("Sorry! you have to wait !!");

Output:

Enter your age: 90

You are eligible to vote !!

Example 2: Program to check whether a number is even or not.

# Simple Python Program to check whether a number is even or not.

num = int(input("enter the number:"))

# Here, we are taking an integer num and taking input dynamically

if num%2 == 0:

# Here, we are checking the condition. If the condition is true, we will enter the block

print("The Given number is an even number")

else:

print("The Given Number is an odd number")

Output:

enter the number: 10

The Given number is even number

The elif statement: The elif statement enables us to check multiple conditions and execute the
specific block of statements depending upon the true condition among them. We can have any
number of elif statements in our program depending upon our need. However, using elif is
optional.

The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.

The syntax of the elif statement is given below.

if expression 1:

35
# block of statements

elif expression 2:

# block of statements

elif expression 3:

# block of statements

else:

# block of statements

Python If-else statements

Example 1

# Simple Python program to understand elif statement

number = int(input("Enter the number?"))

# Here, we are taking an integer number and taking input dynamically

if number==10:

# Here, we are checking the condition. If the condition is true, we will enter the block

print("The given number is equals to 10")

elif number==50:

# Here, we are checking the condition. If the condition is true, we will enter the block

print("The given number is equal to 50");

elif number==100:

# Here, we are checking the condition. If the condition is true, we will enter the block

print("The given number is equal to 100");

else:

print("The given number is not equal to 10, 50 or 100");

Output:

36
Enter the number?15

The given number is not equal to 10, 50 or 100

Example 2

# Simple Python program to understand elif statement

marks = int(input("Enter the marks? "))

# Here, we are taking an integer marks and taking input dynamically

if marks > 85 and marks <= 100:

# Here, we are checking the condition. If the condition is true, we will enter the block

print("Congrats ! you scored grade A ...")

elif marks > 60 and marks <= 85:

# Here, we are checking the condition. If the condition is true, we will enter the block

print("You scored grade B + ...")

elif marks > 40 and marks <= 60:

# Here, we are checking the condition. If the condition is true, we will enter the block

print("You scored grade B ...")

elif (marks > 30 and marks <= 40):

# Here, we are checking the condition. If the condition is true, we will enter the block

print("You scored grade C ...")

else:

print("Sorry you are fail ?")

Output:

Enter the marks? 89

Congrats ! you scored grade A ...

Python Loops

37
The following loops are available in Python to fulfil the looping needs. Python offers 3 choices
for running the loops. The basic functionality of all the techniques is the same, although the
syntax and the amount of time required for checking the condition differ.

We can run a single statement or set of statements repeatedly using a loop command.

The following sorts of loops are available in the Python programming language.

Sr.No.

Name of the loop

Loop Type & Description

 While loop: Repeats a statement or group of statements while a given condition is TRUE. It
tests the condition before executing the loop body.

 For loop: This type of loop executes a code block multiple times and abbreviates the code
that manages the loop variable.

 Nested loops: We can iterate a loop inside another loop.

Loop Control Statements

Statements used to control loops and change the course of iteration are called control statements.
All the objects produced within the local scope of the loop are deleted when execution is
completed.

Python provides the following control statements.

Break statement: This command terminates the loop's execution and transfers the program's
control to the statement next to the loop.

Continue statement: This command skips the current iteration of the loop. The statements
following the continue statement are not executed once the Python interpreter reaches the
continue statement.

Pass statement: The pass statement is used when a statement is syntactically necessary, but no
code is to be executed.

Understanding the Tuples in Python

Tuple is one of the four primary data types in Python. It is a used for storing a collection of
objects. A tuple is quite similar to a Python list in terms of indexing, nested objects, and
repetition; however, the main difference between both is that the tuples in Python are immutable,
unlike the Python list which is mutable.

38
The following is an example of a tuple.

Example:

("Suzuki", "Audi", "BMW"," Skoda ", "Honda") is a tuple.

Key Features of Python Tuple

Tuples are an immutable data type, implying that the data elements of this data type cannot be
changed after they are generated. Each data element in a tuple has a particular order that never
changes as the tuples are ordered sequences.

Forming a Tuple:

All the objects-also known as "elements"-must be separated by a comma, enclosed in parenthesis


(). Although parentheses are not required, they are recommended. Any number of items,
including those with various data types (dictionary, string, float, list, etc.), can be contained in a
tuple.

Let us consider the following example demonstrating the inclusion of different data types in a
tuple:

Code:

# Python program to show how to create a tuple

# Creating an empty tuple

emptyTuple = ()

print("Empty tuple: ", emptyTuple)

# Creating a tuple having integers

integerTuple = (3, 6, 7, 10, 16, 23)

print("Tuple with integers: ", integerTuple)

# Creating a tuple having objects of different data types

mixedTuple = (6, "Javatpoint", 14.3)

print("Tuple with different data types: ", mixedTuple)

# Creating a nested tuple

39
nestedTuple = ("Javatpoint", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))

print("A nested tuple: ", nestedTuple)

Output:

Empty tuple: ()

Tuple with integers: (3, 6, 7, 10, 16, 23)

Tuple with different data types: (6, 'Javatpoint', 14.3)

A nested tuple: ('Javatpoint', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))

Explanation:

In the above snippet of code, we have created four different tuples containing different types of
elements. The first tuple is an empty tuple defined using the parentheses with no element in
between. After that, we have defined an integer tuple consisting of 6 integer values between the
parentheses separated by the commas. The third tuple is comprised of three objects of different
data types – integer, string, and float. At last, we have defined a tuple as a different object,
including another tuple. Moreover, it is not necessary to declare and initialize a tuple using the
parentheses. Let us consider the following example demonstrating the same.

Code:

# Python program to create a tuple without using parentheses

# Creating a tuple

tupleWithoutParentheses = 6, 8.7, "Javatpoint", ["Python", "Tutorials"]

# Displaying the tuple created

print(tupleWithoutParentheses)

# Checking the data type of object tupleWithoutParentheses

print(type(tupleWithoutParentheses) )

# Trying to modify tupleWithoutParentheses

try:

tupleWithoutParentheses[1] = 9.5

except:

40
print("TypeError: Tuples are immutable data types and cannot be modified.")

Output:

(6, 8.7, 'Javatpoint', ['Python', 'Tutorials'])

<class 'tuple'>

TypeError: Tuples are immutable data types and cannot be modified.

Explanation:

In the above snippet of code, we have defined a tuple containing several elements separated by
the commas, without the use of parentheses and printed it for the users. For better clarity, we
have returned its type using the type() method. We have also tried modifying the element of the
tuple using the try and except blocks. As a result, the first line displays the elements of the
tuples. The second line displays the type of the variable which is 'Tuple'. At last, we can observe
a TypeError implying the immutability of the tuples.

Python Built-in Functions

The Python built-in functions are defined as the functions whose functionality is pre-defined in
Python. The python interpreter has several functions that are always present for use. These
functions are known as Built-in Functions. There are several built-in functions in Python which
are listed below:

Python abs() Function

The python abs() function is used to return the absolute value of a number. It takes only one
argument, a number whose absolute value is to be returned. The argument can be an integer and
floating-point number. If the argument is a complex number, then, abs() returns its magnitude.

Python abs() Function Example

# integer number

integer = -20

print('Absolute value of -40 is:', abs(integer))

# floating number

floating = -20.83

print('Absolute value of -40.83 is:', abs(floating))

Output:

41
Absolute value of -20 is: 20

Absolute value of -20.83 is: 20.83

Python all() Function

The python all() function accepts an iterable object (such as list, dictionary, etc.). It returns true if
all items in passed iterable are true. Otherwise, it returns False. If the iterable object is empty, the
all() function returns True.

Python all() Function Example

# all values true

k = [1, 3, 4, 6]

print(all(k))

# all values false

k = [0, False]

print(all(k))

# one false value

k = [1, 3, 7, 0]

print(all(k))

# one true value

k = [0, False, 5]

print(all(k))

# empty iterable

k = []

print(all(k))

Output:

True

42
False

False

False

True

Python bin() Function

The python bin() function is used to return the binary representation of a specified integer. A
result always starts with the prefix 0b.

Python bin() Function Example

x = 10

y = bin(x)

print (y)

Output:

0b1010

Python bool()

The python bool() converts a value to boolean(True or False) using the standard truth testing
procedure.

Python bool() Example

test1 = []

print(test1,'is',bool(test1))

test1 = [0]

print(test1,'is',bool(test1))

test1 = 0.0

print(test1,'is',bool(test1))

test1 = None

print(test1,'is',bool(test1))

43
test1 = True

print(test1,'is',bool(test1))

test1 = 'Easy string'

print(test1,'is',bool(test1))

Output:

[] is False

[0] is True

0.0 is False

None is False

True is True

Easy string is True

Python sum() Function

As the name says, python sum() function is used to get the sum of numbers of an iterable, i.e.,
list.

Python sum() Function Example

s = sum([1, 2,4 ])

print(s)

s = sum([1, 2, 4], 10)

print(s)

Output:

17

Python help() Function

Python help() function is used to get help related to the object passed during the call. It takes an
optional parameter and returns help information. If no argument is given, it shows the Python
help console. It internally calls python's help function.

44
Python help() Function Example

# Calling function

info = help() # No argument

# Displaying result

print(info)

Output:

Welcome to Python 3.5's help utility!

Python Modules

What is Modular Programming?

Modular programming is the practice of segmenting a single, complicated coding task into
multiple, simpler, easier-to-manage sub-tasks. We call these subtasks modules. Therefore, we
can build a bigger program by assembling different modules that act like building blocks.

Modularizing our code in a big application has a lot of benefits.

 Simplification: A module often concentrates on one comparatively small area of the overall
problem instead of the full task. We will have a more manageable design problem to think
about if we are only concentrating on one module. Program development is now simpler and
much less vulnerable to mistakes.

 Flexibility: Modules are frequently used to establish conceptual separations between various
problem areas. It is less likely that changes to one module would influence other portions of
the program if modules are constructed in a fashion that reduces interconnectedness. (We
might even be capable of editing a module despite being familiar with the program beyond
it.) It increases the likelihood that a group of numerous developers will be able to collaborate
on a big project.

 Reusability: Functions created in a particular module may be readily accessed by different


sections of the assignment (through a suitably established api). As a result, duplicate code is
no longer necessary.

 Scope: Modules often declare a distinct namespace to prevent identifier clashes in various
parts of a program.

In Python, modularization of the code is encouraged through the use of functions, modules, and
packages.

45
What are Modules in Python?

A document with definitions of functions and various statements written in Python is called a
Python module.

In Python, we can define a module in one of 3 ways:

Python itself allows for the creation of modules.

Similar to the re (regular expression) module, a module can be primarily written in C


programming language and then dynamically inserted at run-time.

A built-in module, such as the itertools module, is inherently included in the interpreter.

A module is a file containing Python code, definitions of functions, statements, or classes. An


example_module.py file is a module we will create and whose name is example_module.

We employ modules to divide complicated programs into smaller, more understandable pieces.
Modules also allow for the reuse of code.

Rather than duplicating their definitions into several applications, we may define our most
frequently used functions in a separate module and then import the complete module.

How to Import Modules in Python?

In Python, we may import functions from one module into our program, or as we say into,
another module. For this, we make use of the import Python keyword. In the Python window, we
add the next to import keyword, the name of the module we need to import. We will import the
module we defined earlier example_module.

Python OOPs Concepts

Like other general-purpose programming languages, Python is also an object-oriented language


since its beginning. It allows us to develop applications using an Object-Oriented approach. In
Python, we can easily create and use classes and objects. An object-oriented paradigm is to
design the program using classes and objects. The object is related to real-word entities such as
book, house, pencil, etc. The oops concept focuses on writing the reusable code. It is a
widespread technique to solve the problem by creating objects.

Major principles of object-oriented programming system are given below.

46
 Class: The class can be defined as a collection of objects. It is a logical entity that has some
specific attributes and methods. For example: if you have an employee class, then it should
contain an attribute and method, i.e. an email id, name, age, salary, etc.

Syntax

class ClassName:

<statement-1>

<statement-N>

 Object: The object is an entity that has state and behavior. It may be any real-world object
like the mouse, keyboard, chair, table, pen, etc. Everything in Python is an object, and
almost everything has attributes and methods. All functions have a built-in attribute
__doc__, which returns the docstring defined in the function source code.

When we define a class, it needs to create an object to allocate the memory. Consider the
following example.

Example:

class car:

def __init__(self,modelname, year):

self.modelname = modelname

self.year = year

def display(self):

print(self.modelname,self.year)

c1 = car("Toyota", 2016)

c1.display()

Output:

Toyota 2016

47
In the above example, we have created the class named car, and it has two attributes modelname
and year. We have created a c1 object to access the class attribute. The c1 object will allocate
memory for these values. .

 Method: The method is a function that is associated with an object. In Python, a method is
not unique to class instances. Any object type can have methods.

 Inheritance: Inheritance is the most important aspect of object-oriented programming, which


simulates the real-world concept of inheritance. It specifies that the child object acquires all
the properties and behaviors of the parent object. By using inheritance, we can create a class
which uses all the properties and behavior of another class. The new class is known as a
derived class or child class, and the one whose properties are acquired is known as a base
class or parent class. It provides the re-usability of the code.

 Polymorphism: Polymorphism contains two words "poly" and "morphs". Poly means many,
and morph means shape. By polymorphism, we understand that one task can be performed
in different ways. For example - you have a class animal, and all animals speak. But they
speak differently. Here, the "speak" behavior is polymorphic in a sense and depends on the
animal. So, the abstract "animal" concept does not actually "speak", but specific animals
(like dogs and cats) have a concrete implementation of the action "speak".

 Encapsulation: Encapsulation is also an essential aspect of object-oriented programming. It


is used to restrict access to methods and variables. In encapsulation, code and data are
wrapped together within a single unit from being modified by accident.

 Data Abstraction: Data abstraction and encapsulation both are often used as synonyms. Both
are nearly synonyms because data abstraction is achieved through encapsulation. Abstraction
is used to hide internal details and show only functionalities. Abstracting something means
to give names to things so that the name captures the core of what a function or a whole
program does.

48

You might also like