Python Programming
Python Programming
Index
UNIT-I
Python -Introducation
Python-Features,History,Applications,Installation,Examples
Variables,DataTyes,Keywords,Literals,Operators,Comments
UNIT-II
UNIT-III
Python OOPS Concepts
Python Constructors
Python Object Class
Python Inheritance
Abstraction in Python
UNIT-IV
Environment Setup
Database Connection
Creating New Database
Creating Tables
Insert Operation
Read Operation
Update Operation
Join operation Performing Transactions
UNIT-I
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.
Our Python tutorial thoroughly explains Python basics and advanced concepts, starting
with installation, conditional statements, loops, built-in data structures, Object-Oriented
Programming, Generators, Exception Handling, Python RegEx, and many other concepts.
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.
. print("Hello World!")
Compile and Run Python
In Python, it is one line of code. It requires simple syntax to print 'Hello World'
Object-Oriented Language:
It supports object-oriented programming, making writing reusable and modular code easy.
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.
In the following tutorial, we are going to study how Python has become a popular language amongst
programmers. We will also discuss various features of Python that make it a preferred language for the
majority of programmers.
Python At a Glance
Python is a programming language developed by Guido van Rossum in the year 1991 for deploying easy
to complex operations and mathematical functions in less time. Python is an open-source, 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.
Python is a programming language that is used to build software, websites, and applications. It has a wide
range of libraries and modules that make it a suitable language for data analysis, machine learning, and
scientific computing.
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.
#include
using namespace std;
Example:
In the above example, we can observe that the program to print "Hello, Kate!" is verbose in C++ when
compared to Python. Moreover, programming languages like C++ or Java often require more lines of
code to perform simple tasks, such as defining a class, handling exceptions, whereas Python provides
minimal boilerplate, leading to shorter and clearer code.
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
Example:
Value of var_1: 5
Type of var_1:
Value of var_2: 4.7
Type of var_2:
Value of var_3: Welcome
Type of var_3:
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.
i. Standard Library
Python provides a built-in Standard Library support for the programmers. This library includes various
modules for:
This rich standard library reduces the requirement for any external dependencies.
Selenium, BeautifulSoup,
3 Automation and Scripting
requests
These extensive libraries and frameworks are mostly open source and serve as the readymade solutions to
various programming problems and saves a lot of time developing applications. Moreover, with a huge
community support for Python, these libraries constantly undergo updates and improvements for efficient
working. These libraries and frameworks are quite versatile and scalable allowing developers in
developing various applications.
i. Procedural Programming:
Python supports procedural programming where we make use of procedures (functions) in order to
operate on data.
Example:
. # defining a function to perform addition of two numbers
. def sum(a, b):
. # calculating the sum of two numbers and storing the result
. total = a + b
. # returning the result
. return total
.
. if __name__ == '__main__':
. # initializing the variables
. a=5
. b=7
. # calling the sum() function and printing the result
. print(a, "+", b, "=", sum(a, b))
Output:
5 + 7 = 12
Explanation:
In the above snippet of code, we have defined a function as sum() in order to calculate the sum of two
numbers. This function (procedure) is a set of instructions that is operated on the given data to return the
required result.
Example:
. # defining a class
. class Car:
. # constructor
. def __init__(self, make, model, year):
. # initializing variables
. self.make = make
. self.model = model
Make: Nissan
Model: GT-R Skyline
Year: 1999
Explanation:
In the above snippet of code, we have defined a class as Car. Within this class, we have created a
constructor to initialize some variables such as make, model, and year. We have then defined a method to
display the information of the car. We then created an object of the class and accessed the different
attributes and methods of the class. Here, we can observe that the code has been organized in classes and
objects.
Example:
Doubled numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24]
Even numbers: [2, 4, 6, 8, 10, 12]
Sum of numbers: 78
Explanation:
In the above snippet of code, we have performed different operations using the map, filter, and reduce
functions. With the use of these function, we can apply operations on iterables efficiently. As we can
observe, we have doubled the numbers in the given list using the map() function, which allow us to apply
the doubling operation to all the elements in the given iterable. Similarly, the filter() function is used to
filter the elements on the basis of the function. Here, we have filtered out the even numbers from the
given list. At last, we have reduce() function that aggregates the elements using the applied function. In
the above case, we have used the reduce() function to add all the elements of the iterable and return the
sum.
a. Object Creation: Python allocates memory when a new user logs in.
b. Reference Counting: Python tracks the number of references exist to each object.
c. Garbage Collection: When a user logs out and no references remain, Python automatically frees
memory.
a. Multi-threading: This feature allows programmers to run multiple threads within the same
process. It is useful for networking, UI applications, and I/O-heavy tasks.
b. Multiprocessing: This feature allows programmers to run multiple processes with separate
memory spaces. It is useful for CPU-heavy tasks like data processing, image processing and
machine learning.
There is a fact behind choosing the name Python. Guido van Rossum was reading the script of a popular
BBC comedy series "Monty Python's Flying Circus". It was late on-air 1970s.
Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided to select
naming Python after the "Monty Python's Flying Circus" for their newly created programming
language.
The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting.
Python is also versatile and widely used in every technical field, such as Machine Learning, Artificial
Intelligence, Web Development, Mobile Application, Desktop Application, Scientific Calculation, etc.
Python programming language is being updated regularly with new features and supports. There are lots
of update in Python versions, started from 1994 to current release.
The proper way of learning will help us to learn fast and become a good Python developer.
4. Keep Practicing
7. Do small Projects
8. Teach Others
Usage of Python
Python is a general purpose, open source, high-level programming language and also provides number of
libraries and frameworks. Python has gained popularity because of its simplicity, easy syntax and user-
friendly environment.
o Desktop Applications
o Web Applications
o Data Science
o Artificial Intelligence
o Machine Learning
o Scientific Computing
o Robotics
o Internet of Things (IoT)
o Gaming
o Mobile Apps
o Data Analysis and Preprocessing
o Mac: how-to-install-python-on-mac
o CentOS: how-to-install-python-on-centos
o Ubuntu: how-to-install-python-in-ubuntu
This guide describes in detail how to install Python on a Windows system step-by-step.
To install Python on Windows, you first have to take the Python installer from the internet.
r
Windows users
o Latest stable releases, such as Python 3.13.2, are recommended for all users.
o To view the older version, scroll down the page and click on "View all Python releases."
1.3 Installer Download
o To begin, click on the button that has the "Download Python 3.13.2" text.
o
2.2 Selecting Installation Preferences
1. There is "Add Python to PATH," which you will be required to check the box next to it.
o Checking this box will ensure that using the command prompt, you can control the use of Python
at any given location or position.
2. Decide from the given options:
o At this point, your system will have Python files copied into it.
o After completing the process, the statement "Setup was successful" will appear.
o To exit the installer, click on the "Close" button.
To successfully confirm that Python was installed, kindly follow the procedure listed below:
o Open the Command Prompt window by pressing Win + R, followed by typing cmd and pressing
Enter.
4.2 Check Python Version
o To check if the application was successfully installed, type the following command and press
enter:
o In the event Python was installed properly, it will show the following:
In the situation that the command yields an error, it may indicate that Python is not added to the system
PATH.
Pip is known as a package manager, which enables the installation and management of Python libraries.
. $ pip --version
In an effort to test if Python is working correctly, attempt to run basic Python scripts.
2. Type:
. $ python
A Python interactive shell page will open, revealing the Python version with ">>>" following it.
. print("Hello World!")
4. Assuming that Python was installed properly, it will show:
. exit()
Python provides us the feature to execute the Python statement one by one at the interactive prompt. It is
preferable in the case where we are concerned about the output of each line of our Python program.
To open the interactive mode, open the terminal (or command prompt) and type python (python3 in case
if you have Python2 and Python3 both installed on your system).
It will open the following prompt where we can execute the Python statement and check their impact on
the console.
Here, we get the message "Hello World !" printed on the console.
The interpreter prompt is best to run the single-line statements of the code. However, we cannot write the
code every-time on the terminal. It is not suitable to write multiple lines of code.
Using the script mode, we can write multiple lines code into a file which can be executed later. For this
purpose, we need to open an editor like notepad, create a file named and save it with .py extension, which
stands for "Python". Now, we will implement the above example using the script mode.
. print ("hello world"); #here, we have used print() function to print the message on the console.
To run this file named as first.py, we need to run the following command on the terminal.
Step - 1: Open the Python interactive shell, and click "File" then choose "New", it will open a new
blank script in which we can write our code.
Step -2: Now, write the code and press "Ctrl+S" to save the file.
Step - 3: After saving the code, we can run it by clicking "Run" or "Run Module". It will display the
output to the shell.
o We need to type the python keyword, followed by the file name and hit enter to run the Python
file.
Multi-line Statements
Multi-line statements are written into the notepad like an editor and saved it with .py extension. In the
following example, we have defined the execution of the multiple code lines using the Python script.
Code:
The script mode has few advantages and disadvantages as well. Let's understand the following
advantages of running code in script mode.
o We have to save the code every time if we make any change in the code.
o It can be tedious when we run a single or a few lines of code.
JetBrains provides the most popular and a widely used cross-platform IDE PyCharm to run the python
programs.
PyCharm installation
As we have already stated, PyCharm is a cross-platform IDE, and hence it can be installed on a variety of
the operating systems. In this section of the tutorial, we will cover the installation process of PyCharm on
Windows, MacOS, CentOS, and Ubuntu.
Windows
Installing PyCharm on Windows is very simple. To install PyCharm on Windows operating system, visit
the link https://www.jetbrains.com/pycharm/download/download-thanks.html?platform=windows to
download the executable installer. Double click the installer (.exe) file and install PyCharm by clicking
next at each step.
Step - 1. Open Pycharm editor. Click on "Create New Project" option to create new project.
a. We can save the newly created project at desired memory location or can keep file location as it
is but atleast change the project default name untitled to "FirstProject" or something
meaningful.
b. Pycharm automatically found the installed Python interpreter.
c. After change the name click on the "Create" Button.
Step - 3. Click on "File" menu and select "New". By clicking "New" option it will show various file
formats. Select the "Python File".
Step - 4. Now type the name of the Python file and click on "OK". We have written the "FirstProgram".
Indentation is the most significant concept of the Python programming language. Improper use of
indentation will end up "IndentationError" in our code.
Indentation is nothing but adding whitespaces before the statement when it is needed. Without
indentation Python doesn't know which statement to be executed to next. Indentation also defines which
statements belong to which block. If there is no indentation or improper indentation, it will display
"IndentationError" and interrupt our code.
Python indentation defines the particular group of statements belongs to the particular block. The
programming languages such as C, C++, java use the curly braces {} to define code blocks.
In Python, statements that are the same level to the right belong to the same block. We can use four
whitespaces to define indentation. Let's see the following lines of code.
Example -
1
2
3
4
End of for loop
Explanation:
In the above code, for loop has a code blocks and if the statement has its code block inside for loop. Both
indented with four whitespaces. The last print() statement is not indented; that's means it doesn't belong
to for loop.
Comments in Python
Comments are essential for defining the code and help us and other to understand the code. By looking
the comment, we can easily understand the intention of every line that we have written in code. We can
also find the error very easily, fix them, and use in other applications.
In Python, we can apply comments using the # hash character. The Python interpreter entirely ignores the
lines followed by a hash character. A good programmer always uses the comments to make code under
stable. Let's see the following example of a comment.
Types of Comment
Python provides the facility to write comments in two ways- single line comment and multi-line
comment
Single-Line Comment - Single-Line comment starts with the hash # character followed by text for
further explanation.
. """
. This is an example
. Of multi-line comment
. Using triple-quotes
. """
This is the basic introduction of the comments. Visit our Python Comment tutorial to learn it in detail.
Python Identifiers
Python identifiers refer to a name used to identify a variable, function, module, class, module or other
objects. There are few rules to follow while naming the Python Variable.
o A variable name must start with either an English letter or underscore (_).
o A variable name cannot start with the number.
o Special characters are not allowed in the variable name.
o The variable's name is case sensitive.
Let's understand the following example.
Example -
. number = 10
. print(num)
.
. _a = 100
. print(_a)
.
. x_y = 1000
. print(x_y)
Output:
10
100
1000
We have defined the basic syntax of the Python programming language. We must be familiar with the
core concept of any programming languages. Once we memorize the concepts as mentioned above. The
journey of learning Python will become easier.
MacOS
To install PyCharm on MacOS, visit the link https://www.javatpoint.com/how-to-install-pycharm-on-mac.
The link will guide you to install PyCharm on the MacOS.
Ubuntu
To install PyCharm on Ubuntu, visit the link https://www.javatpoint.com/how-to-install-pycharm-in-
ubuntu. The link will guide you to install PyCharm on Ubuntu.
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.
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.
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.
In distinct versions of Python, the preceding keywords might be changed. Some extras may be introduced,
while others may be deleted. By writing the following statement into the coding window, you can
anytime retrieve the collection of keywords in the version you are working on.
Code
Code
. help("keywords")
How to Identify Python Keywords
Python's keyword collection has evolved as new versions were introduced. The await and async
keywords, for instance, were not introduced till Python 3.7. Also, in Python 2.7, the words print and exec
constituted keywords; however, in Python 3+, they were changed into built-in methods and are no longer
part of the set of keywords. In the paragraphs below, you'll discover numerous methods for determining
whether a particular word in Python is a keyword or not.
o A few terms mentioned in the segment following may be unfamiliar to you. They're explained
here, and you must understand what they mean before moving on:
o The Boolean assessment of a variable is referred to as truthfulness. A value's truthfulness reveals
if the value of the variable is true or false.
In the Boolean paradigm, truth refers to any variable that evaluates to true. Pass an item as an input to
bool() to see if it is true. If True is returned, the value of the item is true. Strings and lists which are not
empty, non-zero numbers, and many other objects are illustrations of true values.
False refers to any item in a Boolean expression that returns false. Pass an item as an input to bool() to
see if it is false. If False is returned, the value of the item is false. Examples of false values are " ", 0, { },
and [ ].
True and False are those keywords that can be allocated to variables or parameters and are compared
directly.
Code
. print( 4 == 4 )
. print( 6 > 9 )
. print( True or False )
. print( 9 <= 28 )
. print( 6 > 9 )
. print( True and False )
Output:
True
False
True
True
False
False
Code
print( True == 3 )
. print( False == 0 )
. print( True + True + True)
Output:
False
True
3
The None Keyword
None is a Python keyword that means "nothing." None is known as nil, null, or undefined in different
computer languages.
If a function does not have a return clause, it will give None as the default output:
Code
. print( None == 0 )
. print( None == " " )
. print( None == False )
. A = None
. B = None
. print( A == B )
Output:
False
False
False
True
If a no_return_function returns nothing, it will simply return a None value. None is delivered by
functions that do not meet a return expression in the program flow. Consider the following scenario:
Code
. def no_return_function():
. num1 = 10
. num2 = 20
. addition = num1 + num2
.
. number = no_return_function()
. print( number )
Output:
None
Code
None
Several Python keywords are employed as operators to perform mathematical operations. In many other
computer languages, these operators are represented by characters such as &, |, and!. All of these are
keyword operations in Python:
OR, ∨ || or
NOT, ¬ ! not
CONTAINS, ∈ in
IDENTITY === is
Writers created Python programming with clarity in mind. As a result, many operators in other computer
languages that employ characters in Python are English words called keywords.
The Python keyword and determines whether both the left-hand side and right-hand side operands and
are true or false. The outcome will be True if both components are true. If one is false, the outcome will
also be False:
X Y X and Y
The or Keyword
The or keyword in Python is utilized to check if, at minimum, 1 of the inputs is true. If the first argument
is true, the or operation yields it; otherwise, the second argument is returned:
. <component1> or <component2>
Similarly to the and keyword, the or keyword does not change its inputs to corresponding Boolean values.
Instead, the outcomes are determined based on whether they are true or false.
X Y X or Y
The not keyword in Python is utilized to acquire a variable's contrary Boolean value:
The not keyword is employed to switch the Boolean interpretation or outcome in conditional sentences or
other Boolean equations. Not, unlike and, and or, determines the specific Boolean state, True or False,
afterward returns the inverse.
X not X
True False
False True
Code
False
True
False
The in Keyword
The in keyword of Python is a robust confinement checker, also known as a membership operator. If you
provide it an element to seek and a container or series to seek into, it will give True or False, depending
on if that given element was located in the given container:
. <an_element> in <a_container>
Testing for a certain character in a string is a nice illustration of how to use the in keyword:
Code
. container = "Javatpoint"
. print( "p" in container )
. print( "P" in container )
Output:
True
False
Lists, dictionaries, tuples, strings, or any data type with the method __contains__(), or we can iterate over
it will work with the in keyword.
The is Keyword
In Python, it's used to check the identification of objects. The == operation is used to determine whether
two arguments are identical. It also determines whether two arguments relate to the unique object.
When the objects are the same, it gives True; otherwise, it gives False.
Code
. print( True is True )
. print( False is True )
. print( None is not None )
. print( (9 + 5) is (7 * 2) )
Output:
Code
. print( [] == [] )
. print( [] is [] )
. print( {} == {} )
. print( {} is {} )
Output:
True
False
True
False
A blank dictionary or list is the same as another blank one. However, they aren't identical entities because
they are stored independently in memory. This is because both the list and the dictionary are changeable.
Code
. print( '' == '' )
. print( '' is '' )
Output:
True
True
Strings and tuples, unlike lists and dictionaries, are unchangeable. As a result, two equal strings or tuples
are also identical. They're both referring to the unique memory region.
Code
. def the_outer_function():
. var = 10
. def the_inner_function():
. nonlocal var
. var = 14
. print("The value inside the inner function: ", var)
. the_inner_function()
. print("The value inside the outer function: ", var)
.
. the_outer_function()
Output:
The the_outer_function has a variable named var. Var is not a global variable, as you may have noticed.
As a result, if we wish to change it inside the the_inner_function(), we should declare it using nonlocal.
As a result, the variable was effectively updated within the nested the_inner_function, as evidenced by
the results. The following is what happens if you don't use the nonlocal keyword:
Code
. def the_outer_function():
. var = 10
. def the_inner_function():
. var = 14
. print("Value inside the inner function: ", var)
. the_inner_function()
. print("Value inside the outer function: ", var)
.
. the_outer_function()
Output:
Code
4 5 6 7 8 9 10 11 12 13
2 3 4 5 6 7 8 9 10 14 15 16
except: As previously stated, this operates in conjunction with "try" to handle exceptions.
finally: Whatever the outcome of the "try" section, the "finally" box is implemented every time.
assert: This method is used to help in troubleshooting. Often used to ensure that code is correct. Nothing
occurs if an expression is interpreted as true; however, if it is false, "AssertionError" is raised. An output
with the error, followed by a comma, can also be printed.
Code
. # initializing the numbers
. var1 = 4
. var2 = 0
.
. # Exception raised in the try section
In Python, a null sentence is called a pass. It serves as a stand-in for something else. When it is run,
nothing occurs.
Let's say we possess a function that has not been coded yet however we wish to do so in the long term. If
we write just this in the middle of code,
Code
Code
Code
. class passed_class:
. pass
The None keyword is returned by default if we don't specifically return a value. The accompanying
example demonstrates this.
Code
. def func_with_return():
. var = 13
. return var
.
. def func_with_no_return():
. var = 10
.
. print( func_with_return() )
. print( func_with_no_return() )
Output:
13
None
The del keyword is used to remove any reference to an object. In Python, every entity is an object. We
can use the del command to remove a variable reference.
Code
. var1 = var2 = 5
. del var1
. print( var2 )
. print( var1 )
Output:
5
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [42], in ()
2 del var1
3 print( var2 )
----> 4 print( var1 )
Deleting entries from a collection like a list or a dictionary is also possible with del:
Code
. list_ = ['A','B','C']
. del list_[2]
. print(list_)
Output:
['A', 'B']
Python Literals
Python Literals can be defined as data that is given in a variable or constant.
1. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as well as double
quotes to create a string.
Example:
. "Aman" , '12345'
Types of Strings:
a) Single-line String- Strings that are terminated within a single-line are known as Single line Strings.
Example:
. text1='hello'
b) Multi-line String - A piece of text that is written in multiple lines is known as multiple lines string.
Example:
. text1='hello\
. user'
Example:
. str2='''''welcome
. to
. SSSIT'''
. print str2
Output:
welcome
to
SSSIT
Numeric Literals are immutable. Numeric literals can belong to following four different numerical types.
A Boolean literal can have any of the two values: True or False.
. x = (1 == True)
. y = (2 == False)
. z = (3 == True)
. a = True + 10
. b = False + 10
.
. print("x is", x)
. print("y is", y)
. print("z is", z)
. print("a:", a)
. print("b:", b)
Output:
x is True
y is False
z is False
a: 11
b: 10
None is used to specify to that field that is not created. It is also used for the end of lists in Python.
. val1=10
. val2=None
. print(val1)
. print(val2)
Output:
10
None
V. Literal Collections.
Python provides the four types of literal collection such as List literals, Tuple literals, Dict literals, and
Set literals.
o List contains items of different data types. Lists are mutable i.e., modifiable.
o The values stored in List are separated by comma(,) and enclosed within square brackets([]). We
can store different types of data in a List.
Example - List literals
. list=['John',678,20.4,'Peter']
. list1=[456,'Andrew']
. print(list)
. print(list + list1)
Output:
. tup = (10,20,"Dev",[2,3,4])
. print(tup)
Output:
. set = {'apple','grapes','guava','papaya'}
. print(set)
Output:
Python Operators
In the following tutorial, we will discuss about the operators used in the Python programming language.
1. Arithmetic Operators
2. Comparison Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Let us now discuss these operators used in Python in the following sections.
Arithmetic Operators
Python Arithmetic Operators are used on two operands to perform basic mathematical operators like
addition, subtraction, multiplication, and division. There are different types of arithmetic operators
available in Python including the '+' operator for addition, '-' operator for subtraction, '*' for
multiplication, '/' for division, '%' for modulus, '**' for exponent and '//' for floor division.
Let us consider the following table of arithmetic operators for a detailed explanation.
Now we give code examples of arithmetic operators in Python. The code is given below -
Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -
For a = 46 and b = 4
Calculate the following:
1. Addition of two numbers: a + b = 50
2. Subtraction of two numbers: a - b = 42
3. Multiplication of two numbers: a * b = 184
4. Division of two numbers: a / b = 11.5
5. Floor division of two numbers: a // b = 11
6. Reminder of two numbers: a mod b = 2
7. Exponent of two numbers: a ^ b = 4477456
Comparison Operators
Python Comparison operators are mainly used for the purpose of comparing two values or variables
(operands) and return a Boolean value as either True or False accordingly. There are various types of
comparison operators available in Python including the '==', '!=', '<=', '>=', '<', and '>'.
Let us consider the following table of comparison operators for a detailed explanation.
Now we give code examples of Comparison operators in Python. The code is given below -
Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -
For a = 46 and b = 4
Check the following:
1. Two numbers are equal or not: False
2. Two numbers are not equal or not: True
3. a is less than or equal to b: False
4. a is greater than or equal to b: True
5. a is greater b: True
6. a is less than b: False
Assignment Operators
Using the assignment operators, the right expression's value is assigned to the left operand. Python offers
different assignment operators to assign values to the variable. These assignment operators include '=',
'+=', '-=', '*=', '/=', '%=', '//=', '**=', '&=', '|=', '^=', '>>=', and '<<='.
Let us consider the following table of some commonly used assignment operators for a detailed
explanation.
Now we give code examples of Assignment operators in Python. The code is given below -
a += b: 40
a -= b: 28
a *= b: 204
a /= b: 5.666666666666667
a %= b: 4
a **= b: 1544804416
a //= b: 5
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. There are various Bitwise
operators used in Python, such as bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left
shift (<<), and Right shift (>>). Consider the case below.
For example,
. if a = 7
. b=6
. then, binary (a) = 0111
. binary (b) = 0110
.
. hence, a & b = 0011
. a | b = 0111
. a ^ b = 0100
. ~ a = 1000
. Let, Binary of x = 0101
. Binary of y = 1000
. Bitwise OR = 1101
. 8421
. 1 1 0 1 = 8 + 4 + 1 = 13
.
. Bitwise AND = 0000
. 0000 = 0
.
. Bitwise XOR = 1101
. 8421
. 1 1 0 1 = 8 + 4 + 1 = 13
. Negation of x = ~x = (-x) - 1 = (-5) - 1 = -6
. ~x = -6
Let us consider the following table of bitwise operators for a detailed explanation.
Now we give code examples of Bitwise operators in Python. The code is given below -
Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -
Let us consider the following table of the logical operators used in Python for a detailed explanation.
Logical NOT: If an
expression a is true, then
3 not not a
not (a) will be false and
vice versa.
Program Code:
Now we give code examples of Logical operators in Python. The code is given below -
Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -
Now we give code examples of Membership operators in Python. The code is given below -
. # initializing a list
. myList = [12, 22, 28, 35, 42, 49, 54, 65, 92, 103, 245, 874]
.
. # initializing x and y with some values
. x = 31
. y = 28
.
. # printing the given list
. print("Given List:", myList)
.
. # checking if x is present in the list or not
. if (x not in myList):
. print("x =", x,"is NOT present in the given list.")
. else:
. print("x =", x,"is present in the given list.")
.
. # checking if y is present in the list or not
. if (y in myList):
. print("y =", y,"is present in the given list.")
. else:
. print("y =", y,"is NOT present in the given list.")
Output:
Given List: [12, 22, 28, 35, 42, 49, 54, 65, 92, 103, 245, 874]
x = 31 is NOT present in the given list.
y = 28 is present in the given list.
Identity Operators
Python offers two identity operators as is and is not, that are used to check if two values are located on
the same part of the memory. Two variables that are equal do not imply that they are identical.
Now we give code examples of Identity operators in Python. The code is given below -
Now we compile the above code in python, and after successful compilation, we run it. Then the output is
given below -
a is c => True
a is not c => False
a is b => False
a is not b => True
a == b => True
a != b => False
The order in which the operators are examined is crucial to understand since it tells us which operator
needs to be considered first. Below is a list of the Python operators' precedence tables.
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.
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
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:
Multi-Line Comments
Python does not provide the facility for multi-line comments. However, there are indeed many ways to
create multi-line comments.
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.
Because Python overlooks string expressions that aren't allocated to a variable, we can utilize them as
comments.
Code
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
Since Python is an infer language that is smart enough to determine the type of a variable, we do not need
to specify its type in Python.
Variable names must begin with a letter or an underscore, but they can be a group of both letters and
digits.
The name of the variable should be written in lowercase. Both Rahul and rahul are distinct variables.
Identifier Naming
Identifiers are things like variables. An Identifier is utilized to recognize the literals utilized in the
program. The standards to name an identifier are given underneath.
o Python doesn't tie us to pronounce a variable prior to involving it in the application. It permits us
to make a variable at the necessary time.
o In Python, we don't have to explicitly declare variables. The variable is declared automatically
whenever a value is added to it.
o The equal (=) operator is utilized to assign worth to a variable.
Object References
When we declare a variable, it is necessary to comprehend how the Python interpreter works. Compared
to a lot of other programming languages, the procedure for dealing with variables is a little different.
Python is the exceptionally object-arranged programming language; Because of this, every data item is a
part of a particular class. Think about the accompanying model.
. print("John")
Output:
John
The Python object makes a integer object and shows it to the control center. We have created a string
object in the print statement above. Make use of the built-in type() function in Python to determine its
type.
. type("John")
Output:
. a = 50
. a = 50
. b=a
The variable b refers to the same object that a points to because Python does not create another object.
Let's assign the new value to b. Now both variables will refer to the different objects.
. a = 50
. b =100
.
Python manages memory efficiently if we assign the same variable to two different values.
Object Identity
Every object created in Python has a unique identifier. Python gives the dependable that no two items
will have a similar identifier. The object identifier is identified using the built-in id() function. consider
about the accompanying model.
. a = 50
. b=a
. print(id(a))
. print(id(b))
140734982691168
140734982691168
2822056960944
We assigned the b = a, an and b both highlight a similar item. The id() function that we used to check
returned the same number. We reassign a to 500; The new object identifier was then mentioned.
Variable Names
The process for declaring the valid variable has already been discussed. Variable names can be any
length can have capitalized, lowercase (start to finish, a to z), the digit (0-9), and highlight character(_).
Take a look at the names of valid variables in the following example.
. name = "Devansh"
. age = 20
. marks = 80.50
.
. print(name)
. print(age)
. print(marks)
Output:
Devansh
20
80.5
Consider the following valid variables name.
. name = "A"
. Name = "B"
. naMe = "C"
. NAME = "D"
. n_a_m_e = "E"
. _name = "F"
. name_ = "G"
. _name_ = "H"
. na56me = "I"
.
. print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name, na56me)
Output:
ABCDEDEFGFI
We have declared a few valid variable names in the preceding example, such as name, _name_, and so on.
However, this is not recommended because it may cause confusion when we attempt to read code. To
make the code easier to read, the name of the variable ought to be descriptive.
We can apply different tasks in two ways, either by relegating a solitary worth to various factors or
doling out numerous qualities to different factors. Take a look at the following example.
Eg:
. x=y=z=50
. print(x)
. print(y)
. print(z)
Output:
50
50
50
2. Assigning multiple values to multiple variables:
Eg:
. a,b,c=5,10,15
. print a
. print b
. print c
Output:
5
10
15
The values will be assigned in the order in which variables appear.
Local Variable
The variables that are declared within the function and have scope within the function are known as local
variables. Let's examine the following illustration.
. # Declaring a function
. def add():
. # Defining local variables. They has scope only within a function
. a = 20
. b = 30
. c=a+b
. print("The sum is:", c)
.
. # Calling a function
. add()
Output:
We declared the function add() and assigned a few variables to it in the code above. These factors will be
alluded to as the neighborhood factors which have scope just inside the capability. We get the error that
follows if we attempt to use them outside of the function.
. add()
. # Accessing local variable outside the function
. print(a)
Output:
Global Variables
Global variables can be utilized all through the program, and its extension is in the whole program.
Global variables can be used inside or outside the function.
By default, a variable declared outside of the function serves as the global variable. Python gives the
worldwide catchphrase to utilize worldwide variable inside the capability. The function treats it as a local
variable if we don't use the global keyword. Let's examine the following illustration.
Example -
101
Welcome To Javatpoint
Welcome To Javatpoint
Explanation:
In the above code, we declare a global variable x and give out a value to it. We then created a function
and used the global keyword to access the declared variable within the function. We can now alter its
value. After that, we gave the variable x a new string value and then called the function and printed x,
which displayed the new value.
Delete a variable
We can delete the variable using the del keyword. The syntax is given below.
Syntax -
. del <variable_name>
In the following example, we create a variable x and assign value to it. We deleted variable x, and print it,
we get the error "variable x is not defined". The variable x will no longer use in future.
Example -
. # Assigning a value to x
. x=6
. print(x)
. # deleting a variable.
. del x
. print(x)
Output:
6
Traceback (most recent call last):
File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/multiprocessing.py", line 389, in
print(x)
NameError: name 'x' is not defined
Maximum Possible Value of an Integer in Python
Python, to the other programming languages, does not support long int or float data types. It uses the int
data type to handle all integer values. The query arises here. In Python, what is the maximum value that
the variable can hold? Take a look at the following example.
<class 'int'>
10000000000000000000000000000000000000000001
As we can find in the above model, we assigned a large whole number worth to variable x and really look
at its sort. It printed class <int> not long int. As a result, the number of bits is not limited, and we are free
to use all of our memory.
We can print numerous factors inside the single print explanation. The examples of single and multiple
printing values are provided below.
5
5
Example - 2 (Printing Multiple Variables)
. a=5
. b=6
. # printing multiple variables
. print(a,b)
. # separate the variables by the comma
. Print(1, 2, 3, 4, 5, 6, 7, 8)
Output:
56
12345678
Basic Fundamentals:
This section contains the fundamentals of Python, such as:
a)Tokens:
o The tokens can be defined as a punctuator mark, reserved words, and each word in a statement.
o The token is the smallest unit inside the given program.
There are following tokens in Python:
o Keywords.
o Identifiers.
o Literals.
o Operators.
. 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.
1. Numbers
2. Sequence Type
3. Boolean
The data types will be briefly discussed in this tutorial section. We will talk about every single one of
them exhaustively later in this instructional exercise.
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:
o 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.
o Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to within
15 decimal places.
o 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
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.
Example - 1
Example - 2
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
List
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 (*).
Example:
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.
Example:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
The comma (,) and the curly braces are used to separate the items in the dictionary.
<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.
Python also allows us to delete the reference of a number by using the del keyword. For example, del a
will delete the object a declared above.
In Python, there are four types of numbers that can be assigned to a variable given as follows.
o Int (signed Integer object) : they are the negative or non-negative numbers with no decimal
point. There is no limit on an integer in python. However, the size of the integer is constrained by
the amount of the memory our system has.
Python also provides the support for various number systems like binary, hexadecimal, and octal
values. To store values in different number systems, consider the following pattern.
0b10 = 2 (decimal)
0b
Binary 2 0b1010 = 10 (decimal)
0B
0B101 = 5 (decimal)
0o10 = 8
0o
Octal 8 0o12 = 10
0O
0O132 =decimal
0xA = 10
0x
Hexadecimal 16 0xB = 11
0X
0XBE = 190
For example, while accepting the value from the user using the input() function, we have to convert the
entered string by the user to integer explicitly if we need an integer value.
Example
. i="123456"
. print(type(i))
. num = int(i)
. print(num)
. print(type(num))
. j = 190.98
. print(int(j));
Output:
<class 'str'>
123456
<class 'int'>
190
Type Casting in Python (Implicit and Explicit) with Examples
Introduction
In the domain of Python programming, the capacity to control information flawlessly is critical. Integral
to this capacity is type casting, likewise alluded to as type change. Type casting includes changing the
information kind of a variable starting with one structure then onto the next. In Python, this change can
happen either verifiably, where the translator consequently plays out the transformation, or expressly,
where the developer determines the transformation.
Type casting, on a very basic level, is the method involved with changing the information kind of a
variable. It empowers Python designers to explore the powerful idea of the language by working with
changes between divergent information types. This change guarantees that information can be used
properly inside the setting of a program.
Type giving serves a role as a key part in Python programming, empowering consistent information
control. Its importance lies in its capacity to adjust information to the necessities of a program,
subsequently upgrading adaptability and usefulness. By working with the change between various
information types, type casting enables designers to handle different programming difficulties effortlessly.
Numeric Types:
o str: Addresses strings, successions of Unicode characters encased inside single, twofold, or triple
statements.
o list: Addresses records, requested assortments of things encased inside square sections [ ].
Records are variable, meaning their components can be adjusted after creation.
o tuple: Addresses tuples, requested assortments of things encased inside brackets ( ). Tuples are
changeless, meaning their components can't be altered after creation.
o range: Addresses a succession of numbers produced by the reach() capability.
Mapping Type:
o dict: Addresses word references, unordered assortments of key-esteem matches encased inside
wavy supports { }. Word references are changeable and permit quick recovery of values in light
of keys.
Set Types:
o set: Addresses sets, unordered assortments of one of a kind components encased inside wavy
supports { }. Sets don't permit copy components.
o frozenset: Addresses frozensets, unchanging sets whose components can't be changed after
creation.
Boolean Sort:
o bool: Addresses boolean qualities, Valid or Misleading, utilized for sensible tasks and
correlations.
Binary Types:
o bytes: Addresses successions of bytes, unchanging arrangements of whole numbers in the reach 0
to 255.
o bytearray: Addresses variable groupings of bytes, like bytes protests however changeable.
Implicit type casting, otherwise called programmed type change, is a cycle where the Python translator
consequently changes over one information type to one more without the requirement for express
directions from the developer. This transformation happens consistently during activities including
operands of various information types.
While performing activities, like number-crunching tasks or examinations, with operands of various
information types, Python's mediator insightfully deals with the change cycle to guarantee similarity. The
mediator switches the operands over completely to a typical information type in view of specific
principles characterized inside the language.
Significance:
Understood type casting assumes a critical part in improving on code and upgrading adaptability.
By permitting programmed change between information types, Python empowers software engineers to
zero in on the rationale of their code without agonizing over the complexities of type similarity.
Explicit type casting, otherwise called manual sort change, alludes to the most common way of changing
over a worth starting with one information type then onto the next unequivocally utilizing predefined
capabilities or techniques given by the programming language. In Python, express sort casting permits
designers to exactly control how information is changed over between various kinds, guaranteeing
similarity and rightness in tasks.
In express sort casting, the software engineer determines the ideal transformation utilizing worked in
capabilities or constructors given by Python. This approach offers clearness and straightforwardness in
code, making it express to different designers or perusers how information types are being controlled.
Python gives a bunch of implicit capabilities explicitly intended for type casting. These capabilities
permit software engineers to change over values between different information types consistently. A
portion of the generally involved capabilities for unequivocal sort casting include:
o Automatic: Happens flawlessly without unequivocal directions from the software engineer.
o Handled by Interpreter: The Python translator deals with the change cycle during activities
including operands of various information types.
o Convenience: Improves on code via naturally changing over information types depending on the
situation, diminishing the requirement for express sort transformation proclamations.
Explicit Type Casting:
o Manual: Requires express guidelines from the software engineer utilizing predefined capabilities
or strategies.
o Programmer Control: Designers have exact command over the change interaction, determining
the ideal information type transformation.
o Clarity and Precision: Offers straightforwardness and lucidity in code, making it unequivocal
how information types are being controlled.
Python String
Till now, we have discussed numbers as the standard data-types in Python. In this section of the tutorial,
we will discuss the most popular data type in Python, i.e., string.
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple
quotes. The computer does not understand the characters; internally, it stores manipulated character as
the combination of the 0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also
called the collection of Unicode characters.
In Python, strings can be created by enclosing the character or the sequence of characters in the quotes.
Python allows us to use single quotes, double quotes, or triple quotes to create the string.
Syntax:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Python Boolean
Python includes a built-in data type called Boolean, which can be either True or False. This type is
commonly used to represent the outcome of logical comparisons or conditions.
Examples:
. Input: 19 == 19
. Output: True
. Input: 24 < 19
. Output: False
Python Boolean Type
A Boolean type can only have two possible values: True or False. The variable's data type is shown as
Boolean by the output <class 'bool'>.
This Python program shows how to find the data type of variables using the type() method. The data type,
'bool' (Boolean), is returned by type(p), and an is assigned the Boolean value True in the code. Similar to
this, type(q) yields 'bool,' and b is given the Boolean value False.
Output:
Syntax:
. bool([x])
Python bool() Function
You can also check if something is true or false without using the bool() function. Following a
comparison, the Boolean values will be given back. When the equality comparison is performed in the
example below, the Boolean value False will be present in the variable res.
.
. # a Python program demonstrating the
. # working of the built-in bool() method
. p = 18
. q = 40
. print(bool(p == q)) # Returns False since p and q are not equal.
. p = None
. print(bool(p)) # Returns False as p is None
. p = ()
. print(bool(p)) # Returns False as the sequence p is empty.
. p = {}
. print(bool(p)) # Returns False as the sequence p is mapping
. p = 0.0
. print(bool(p)) # Returns False as p is 0
. p = 'JavaTpoint'
. print(bool(p)) # Since p is a non-empty string, it returns True.
Program Explanation:
This Python program shows how to use the built-in bool() method to determine whether or not various
values are true. Since 18 and 40 are not equal, it checks if p is equal to q in the first case, which returns
False. The subsequent case checks the Boolean value of p when it is set to None, which returns False.
Since the tuple p in the third case is empty, the outcome is False. Likewise, the fourth case looks at a
vacant word, map p, returning False. The fifth case assesses the Boolean value of p when it is set to 0.0,
resulting in False. The program concludes by evaluating the Boolean value of the non-empty string p
('JavaTpoint'), which is True. This program demonstrates how the Python bool() method can be used to
evaluate the truthiness of various data types and expressions.
Output:
False
False
False
False
False
True
Statement Description
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.
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
. 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:
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
. if condition:
. #block of statements
. else:
. #another block of statements (else-block)
he 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.
. if expression 1:
. # block of statements
.
. elif expression 2:
. # block of statements
.
. elif expression 3:
. # block of statements
.
. else:
. # block of statements
Example 1
he 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.
. if expression 1:
. # block of statements
.
. elif expression 2:
. # block of statements
.
. elif expression 3:
. # block of statements
.
. else:
. # block of statements
.
Python Loops
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.
Python provides the following control statements. We will discuss them later in detail.
Loop iterates until the final item of the sequence are reached.
Code
The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]
As already said, a for loop executes the code block until the sequence element is reached. The statement
is written right after the for loop is executed after the execution of the for loop is complete.
Only if the execution is complete does the else statement comes into play. It won't be executed if we exit
the loop or if an error is thrown.
Code
P
y
t
h
If block
n
L
If block
If block
p
Now similarly, using else with for loop.
Syntax:
. # Python program to show how to use else statement with for loop
.
. # Creating a sequence
. tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)
.
. # Initiating the loop
. for value in tuple_:
. if value % 2 != 0:
. print(value)
. # giving an else statement
. else:
. print("These are the odd numbers present in the tuple")
Output:
3
9
3
9
7
These are the odd numbers present in the tuple
With the help of the range() function, we may produce a series of numbers. range(10) will produce values
between 0 and 9. (10 numbers).
We can give specific start, stop, and step size values in the manner range(start, stop, step size). If the step
size is not specified, it defaults to 1.
Since it doesn't create every value it "contains" after we construct it, the range object can be characterized
as being "slow." It does provide in, len, and __getitem__ actions, but it is not an iterator.
Code
range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]
To iterate through a sequence of items, we can apply the range() method in for loops. We can use
indexing to iterate through the given sequence by combining it with an iterable's len() function. Here's an
illustration.
Code
PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE
While Loop
While loops are used in Python to iterate until a specified condition is met. However, the statement in the
program that follows the while loop is executed once the condition changes to false.
. while <condition>:
. { code block }
All the coding statements that follow a structural command define a code block. These statements are
intended with the same number of spaces. Python groups statements together with indentation.
Code
As discussed earlier in the for loop section, we can use the else statement with the while loop also. It has
the same syntax.
Code
. #Python program to show how to use else statement with the while loop
. counter = 0
.
. # Iterating through the while loop
. while (counter < 10):
. counter = counter + 3
. print("Python Loops") # Executed untile condition is met
. # Once the condition of while loop gives False this statement will be executed
. else:
. print("Code block inside the else statement")
Output:
Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement
The loop can be declared in a single statement, as seen below. This is similar to the if-else block, where
we can write the code block in a single line.
Code
Now we will discuss the loop control statements in detail. We will see an example of each control
statement.
Continue Statement
Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:
Current Letter: L
Current Letter: s
Break Statement
It stops the execution of the loop when the break statement is reached.
Code
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Current Letter:
Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for classes, functions,
and empty control statements.
Code
Last Letter: s
Python is a strong, universally applicable prearranging language planned to be easy to comprehend and
carry out. It is allowed to get to because it is open-source. In this tutorial, we will learn how to use
Python for loops, one of the most fundamental looping instructions in Python programming.
In coding, loops are designed to execute a specified code block repeatedly. We'll learn how to construct a
while loop in Python, the syntax of a while loop, loop controls like break and continue
. Statement
. while Condition:
. Statement
Python List
In Python, the sequence of various data types is stored in a list. A list is a collection of different kinds of
values or items. Since Python lists are mutable, we can change their elements after forming. The comma
(,) and the square brackets [enclose the List's items] serve as separators.
Although six Python data types can hold sequences, the List is the most common and reliable form. A list,
a type of sequence data, is used to store the collection of data. Tuples and Strings are two similar data
formats for sequences.
Lists written in Python are identical to dynamically scaled arrays defined in other languages, such as
Array List in Java and Vector in C++. A list is a collection of items separated by commas and denoted by
the symbol [].
List Declaration
. # example
. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
. b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]
. a == b
Output:
False
The indistinguishable components were remembered for the two records; however, the subsequent
rundown changed the file position of the fifth component, which is against the rundowns' planned request.
False is returned when the two lists are compared.
Code
. # example
. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
. b = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
. a == b
Output:
True
Records forever protect the component's structure. Because of this, it is an arranged collection of things.
Code
The index ranges from 0 to length -1. The 0th index is where the List's first element is stored; the 1st
index is where the second element is stored, and so on.
. list_varible(start:stop:step)
Python Tuples
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.
Example:
1. Tuples are an immutable data type, implying that the data elements of this data type cannot be
changed after they are generated.
2. 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:
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))
Lists and tuples are types of data structures that hold one or more than one objects or items in a
predefined order. We can contain objects of any data type in a list or tuple, including the null data type
defined by the None Keyword.
What is a List?
In other programming languages, list objects are declared similarly to arrays. Lists don't have to be
homogeneous all the time, so they can simultaneously store items of different data types. This makes lists
the most useful tool. The list is a kind of container data Structure of Python that is used to hold numerous
pieces of data simultaneously. Lists are helpful when we need to iterate over some elements and keep
hold of the items.
What is a Tuple?
A tuple is another data structure to store the collection of items of many data types, but unlike mutable
lists, tuples are immutable. A tuple, in other words, is a collection of items separated by commas.
Because of its static structure, the tuple is more efficient than the list.
In most cases, lists and tuples are equivalent. However, there are some important differences to be
explored in this article.
Example Code
. # Python code to show the difference between creating a list and a tuple
.
. list_ = [4, 5, 7, 1, 7]
. tuple_ = (4, 1, 8, 3, 9)
.
. print("List is: ", list_)
. print("Tuple is: ", tuple_)
Output:
Python Set
A Python set is the collection of the unordered items. Each element in the set must be unique, immutable,
and the sets remove the duplicate elements. Sets are mutable which means we can modify it after its
creation.
Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we cannot
directly access any element of the set by the index. However, we can print them all together, or we can
get the list of elements by looping through the set.
Creating a set
The set can be created by enclosing the comma-separated immutable items with the curly braces {}.
Python also provides the set() method, which can be used to create the set by the passed sequence.
Python Dictionary
Dictionaries are a useful data structure for storing data in Python because they are capable of imitating
real-world data arrangements where a certain value exists for a given key.
Curly brackets are the simplest way to generate a Python dictionary, although there are other approaches
as well. With many key-value pairs surrounded in curly brackets and a colon separating each key from its
value, the dictionary can be built. (:). The following provides the syntax for defining the dictionary.
Syntax:
Python Functions
This tutorial will go over the fundamentals of Python functions, including what they are, their syntax,
their primary parts, return keywords, and significant types. We'll also look at some examples of Python
function definitions.
A collection of related assertions that carry out a mathematical, analytical, or evaluative operation is
known as a function. An assortment of proclamations called Python Capabilities returns the specific
Client-characterized and worked-in capabilities are the two primary classes of capabilities in Python. It
aids in maintaining the program's uniqueness, conciseness, and structure.
Pause We can stop a program from repeatedly using the same code block by including functions.
o Once defined, Python functions can be called multiple times and from any location in a program.
o Our Python program can be broken up into numerous, easy-to-follow functions if it is significant.
o The ability to return as many outputs as we want using a variety of arguments is one of Python's
most significant achievements.
o However, Python programs have always incurred overhead when calling functions.
However, calling functions has always been overhead in a Python program.
Syntax
We will define a function that returns the argument number's square when called.
When the fundamental framework for a function is finished, we can call it from anywhere in the program.
An illustration of how to use the a_function function can be found below.
Code
The following are the types of arguments that we can use to call a function:
1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments
1) Default Arguments
A default contention is a boundary that takes as information a default esteem, assuming that no worth is
provided for the contention when the capability is called. The following example demonstrates default
arguments.
Code
We can eliminate or orchestrate specific contentions in an alternate request since the Python translator
will interface the furnished watchwords to connect the qualities with its boundaries. One more method
for utilizing watchwords to summon the capability() strategy is as per the following:
3) Required Arguments
Required arguments are those supplied to a function during its call in a predetermined positional
sequence. The number of arguments required in the method call must be the same as those provided in
the function's definition.
We should send two contentions to the capability() all put together; it will return a language structure
blunder, as seen beneath.
Code
. # Python code to demonstrate the use of default arguments
. # Defining a function
. def function( n1, n2 ):
. print("number 1 is: ", n1)
. print("number 2 is: ", n2)
.
. # Calling function and passing two arguments out of order, we need num1 to be 20 and num2 to
be 30
. print( "Passing out of order arguments" )
. function( 30, 20 )
.
. # Calling function and passing only one argument
. print( "Passing only one argument" )
4) Variable-Length Arguments
We can involve unique characters in Python capabilities to pass many contentions. However, we need a
capability. This can be accomplished with one of two types of characters:
Code
. # Python code to demonstrate the use of variable-length arguments
. # Defining a function
. def function( *args_list ):
. ans = []
. for l in args_list:
. ans.append( l.upper() )
. return ans
. # Passing args arguments
. object = function('Python', 'Functions', 'tutorial')
. print( object )
.
. # defining a function
. def function( **kargs_list ):
. ans = []
. for key, value in kargs_list.items():
. ans.append([key, value])
. return ans
. # Paasing kwargs arguments
. object = function(First = "Python", Second = "Functions", Third = "Tutorial")
. print(object)
Output:
When a defined function is called, a return statement is written to exit the function and return the
calculated value.
Syntax:
Code
Since we do not use the def keyword to declare these kinds of Python functions, they are unknown. The
lambda keyword can define anonymous, short, single-output functions.
Arguments can be accepted in any number by lambda expressions; However, the function only produces
a single value from them. They cannot contain multiple instructions or expressions. Since lambda needs
articulation, a mysterious capability can't be straightforwardly called to print.
In contrast to inline expressions in C and C++, which pass function stack allocations at execution for
efficiency reasons, lambda expressions appear to be one-line representations of functions.
Syntax
Lambda functions have exactly one line in their syntax:
Code
. # Python code to demonstrate ananymous functions
. # Defining a function
. lambda_ = lambda argument1, argument2: argument1 + argument2;
.
. # Calling the function and passing values
. print( "Value of the function is : ", lambda_( 20, 30 ) )
. print( "Value of the function is : ", lambda_( 40, 50 ) )
Output:
The length of time a variable remains in RAM is its lifespan. The lifespan of a function is the same as the
lifespan of its internal variables. When we exit the function, they are taken away from us. As a result, the
value of a variable in a function does not persist from previous executions.
Code
This is because the capability's interior variable num is not quite the same as the outer variable (nearby to
the capability). Despite having a similar variable name, they are separate factors with discrete extensions.
Factors past the capability are available inside the capability. The impact of these variables is global. We
can retrieve their values within the function, but we cannot alter or change them. The value of a variable
can be changed outside of the function if it is declared global with the keyword global.
A function defined within another is called an "inner" or "nested" function. The parameters of the outer
scope are accessible to inner functions. Internal capabilities are developed to cover them from the
progressions outside the capability. Numerous designers see this interaction as an embodiment.
Code
Python bool()
The python bool() converts a value to boolean(True or False) using the standard truth testing procedure.
Python bytes()
The python bytes() in Python is used for returning a bytes object. It is an immutable version of the
bytearray() function.
Python bytearray()
The python bytearray() returns a bytearray object and can convert objects into bytearray objects, or
create an empty bytearray object of the specified size.
Python float()
The python float() function returns a floating-point number from a number or string.
Python frozenset()
The python frozenset() function returns an immutable frozenset object initialized with elements from the
given iterable.
A Symbol table is defined as a data structure which contains all the necessary information about the
program. It includes variable names, methods, classes, etc.
Python list()
The python list() creates a list in python.
Python object()
The python object() returns an empty object. It is a base for all the classes and holds the built-in
properties and methods which are default for all the classes.
Python dict()
Python dict() function is a constructor which creates a dictionary. Python dictionary provides three
different constructors to create a dictionary:
Hashable types: * bool * int * long * float * string * Unicode * tuple * code object.
Etc
Syntax
The syntax of the Lambda Function is given below -
Lambda functions can be used whenever function arguments are necessary. In addition to other forms of
formulations in functions, it has a variety of applications in certain coding domains. It's important to
remember that according to syntax, lambda functions are limited to a single statement.
Example
Here we share some examples of lambda functions in Python for learning purposes. Program Code 1:
Now we gave an example of a lambda function that adds 4 to the input number is shown below.
. # Code to demonstrate how we can use a lambda function for adding 4 numbers
. add = lambda num: num + 4
. print( add(6) )
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -
10
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.
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.
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.
Modules in Python
A document with definitions of functions and various statements written in Python is called a Python
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.
Let's construct a module. Save the file as example_module.py after entering the following.
Example:
. # Here, we are creating a simple Python program to show how to create a module.
. # defining a function in the module to reuse it
. def square( number ):
. # here, the above function will square the number passed as the input
. result = number ** 2
. return result # here, we are returning the result of the function
Here, a module called example_module contains the definition of the function square(). The function
returns the square of a given number.
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.
Syntax:
. import example_module
The functions that we defined in the example_module are not immediately imported into the present
program. Only the name of the module, i.e., example_ module, is imported here.
We may use the dot operator to use the functions using the module name. For instance:
Example:
. # here, we are calling the module square method and passing the value 4
. result = example_module.square( 4 )
. print("By using the module square of number is: ", result )
Output:
Python Exceptions
When a Python program meets an error, it stops the execution of the rest of the program. An error in
Python might be either an error in the syntax of an expression or a Python exception. We will see what an
exception is. Also, we will see the difference between a syntax error and an exception in this tutorial.
Following that, we will learn about trying and except blocks and how to raise exceptions and make
assertions. After that, we will see the Python exceptions list.
What is an Exception?
An exception in Python is an incident that happens while executing a program that causes the regular
course of the program's commands to be disrupted. When a Python code comes across a condition it can't
handle, it raises an exception. An object in Python that describes an error is called an exception.
When a Python code throws an exception, it has two options: handle the exception immediately or stop
and quit.
Code
if (s != o:
^
SyntaxError: invalid syntax
The arrow in the output shows where the interpreter encountered a syntactic error. There was one
unclosed bracket in this case. Close it and rerun the program:
Code
. #Python code after removing the syntax error
. string = "Python Exceptions"
.
. for s in string:
. if (s != o):
. print( s )
Output:
Code
. # Python code to catch an exception and handle it using try and except code blocks
.
. a = ["Python", "Exceptions", "try and except"]
. try:
. #looping through the elements of the array a, choosing a range that goes beyond the length of
the array
. for i in range( 4 ):
. print( "The index and element from the array is", i, a[i] )
. #if an error occurs in the try block, then except block will be executed by the Python interpreter
. except:
If we wish to use raise to generate an exception when a given condition happens, we may do so as
follows:
Code
. #Python code to show how to raise an exception in Python
. num = [3, 4, 5, 7]
. if len(num) > 3:
. raise Exception( f"Length of the given list must be less than or equal to 3 but is {len(num)}" )
Output:
1 num = [3, 4, 5, 7]
2 if len(num) > 3:
----> 3 raise Exception( f"Length of the given list must be less than or equal to 3 but is {len(num)}" )
Exception: Length of the given list must be less than or equal to 3 but is 4
The implementation stops and shows our exception in the output, providing indications as to what went
incorrect.
Assertions in Python
When we're finished verifying the program, an assertion is a consistency test that we can switch on or off.
The simplest way to understand an assertion is to compare it with an if-then condition. An exception is
thrown if the outcome is false when an expression is evaluated.
Assertions are made via the assert statement, which was added in Python 1.5 as the latest keyword.
Assertions are commonly used at the beginning of a function to inspect for valid input and at the end of
calling the function to inspect for valid output.
Code
. #Python program to show how to use assert keyword
. # defining a function
. def square_root( Number ):
. assert ( Number < 0), "Give a positive integer"
. return Number**(1/2)
.
. #Calling function and passing the values
. print( square_root( 36 ) )
. print( square_root( -36 ) )
Output:
Code
. # Python program to show how to use else clause with try and except clauses
.
. # Defining a function which returns reciprocal of a number
. def reciprocal( num1 ):
. try:
. reci = 1 / num1
. except ZeroDivisionError:
. print( "We cannot divide by zero" )
. else:
. print ( reci )
. # Calling the function and passing values
0.25
We cannot divide by zero
The finally keyword is available in Python, and it is always used after the try-except block. The finally
code block is always executed after the try block has terminated normally or after the try block has
terminated for some other reason.
Code
. # Python code to show the use of finally clause
.
. # Raising an exception in try block
. try:
. div = 4 // 0
. print( div )
. # this block will handle the exception raised
. except ZeroDivisionError:
. print( "Atepting to divide by zero" )
. # this will always be executed no matter exception is raised or not
. finally:
. print( 'This is code of finally clause' )
Output:
Here is an illustration of a RuntimeError. In this case, a class that derives from RuntimeError is produced.
Once an exception is detected, we can use this to display additional detailed information.
We raise a user-defined exception in the try block and then handle the exception in the except block. An
example of the class EmptyError is created using the variable var.
Code
. class EmptyError( RuntimeError ):
. def __init__(self, argument):
. self.arguments = argument
. Once the preceding class has been created, the following is how to raise an exception:
. Code
. var = " "
. try:
2 try:
----> 3 raise EmptyError( "The variable is empty" )
4 except (EmptyError, var):
In Python, the date is not a data type, but we can work with the date objects by importing the module
named with datetime, time, and calendar.
In this section of the tutorial, we will discuss how to work with the date and time objects in Python.
. # Importing re module
. import re
The re-module in Python gives full support for regular expressions of Pearl style. The re module raises
the re.error exception whenever an error occurs while implementing or using a regular expression.
But first, a minor point: many letters have a particular meaning when utilized in a regular
expression called metacharacters.
The majority of symbols and characters will easily match. (A case-insensitive feature can be enabled,
allowing this RE to match Python or PYTHON.) For example, the regular expression 'check' will match
exactly the string 'check'.
There are some exceptions to this general rule; certain symbols are special metacharacters that don't
match. Rather, they indicate that they must compare something unusual or have an effect on other parts
of the RE by recurring or modifying their meaning.
As the name suggests, there are some characters with special meanings:
Characters Meaning
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.
o Class
o Object
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o Encapsulation
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):
Toyota 2016
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. We will learn more about class and object in the next tutorial.
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.
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.
Object-oriented programming is
Procedural programming uses a
the problem-solving approach
1. list of instructions to do
and used where computation is
computation step by step.
done by using objects.
In procedural programming, It
It makes the development and is not easy to maintain the
2.
maintenance easier. codes when the project
becomes lengthy.
Classes in Python:
Suppose a class is a prototype of a building. A building contains all the details about the floor, rooms,
doors, windows, etc. we can make as many buildings as we want, based on these details. Hence, the
building can be seen as a class, and we can create as many objects of this class.
Syntax
. class ClassName:
. #statement_suite
In Python, we must notice that each class is associated with a documentation string which can be
accessed by using <class-name>.__doc__. A class contains a statement suite including fields,
constructor, function, etc. definition.
Python Constructor
A constructor is a special type of method (function) which is used to initialize the instance members of
the class.
In C++ or Java, the constructor has the same name as its class, but it treats constructor differently in
Python. It is used to create an object.
1. Parameterized Constructor
2. Non-parameterized Constructor
Constructor definition is executed when we create the object of this class. Constructors also verify that
there are enough resources for the object to perform any start-up task.
We can pass any number of arguments at the time of creating the class object, depending upon
the __init__() definition. It is mostly used to initialize the class attributes. Every class must have a
constructor, even if it simply relies on the default constructor.
Example
ID: 101
Name: John
ID: 102
Name: David
Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code reusability
to the program because we can use an existing class to create a new class instead of creating it from
scratch.
In inheritance, the child class acquires the properties and can access all the data members and functions
defined in the parent class. A child class can also provide its specific implementation to the functions of
the parent class. In this section of the tutorial, we will discuss inheritance in detail.
In python, a derived class can inherit base class by just mentioning the base in the bracket after the
derived class name. Consider the following syntax to inherit a base class into the derived class.
Syntax
. class derived-class(base class):
. <class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the following
syntax.
. class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
. <class - suite>
Example 1
. class Animal:
. def speak(self):
. print("Animal Speaking")
. #child class Dog inherits the base class Animal
. class Dog(Animal):
. def bark(self):
. print("dog barking")
. d = Dog()
. d.bark()
. d.speak()
Output:
dog barking
Animal Speaking
Multi-Level inheritance is possible in python like other object-oriented languages. Multi-level inheritance
is archived when a derived class inherits another derived class. There is no limit on the number of levels
up to which, the multi-level inheritance is archived in python.
Syntax
. class class1:
. <class-suite>
. class class2(class1):
. <class suite>
. class class3(class2):
. <class suite>
. class Animal:
. def speak(self):
. print("Animal Speaking")
. #The child class Dog inherits the base class Animal
. class Dog(Animal):
. def bark(self):
. print("dog barking")
. #The child class Dogchild inherits another child class Dog
. class DogChild(Dog):
. def eat(self):
. print("Eating bread...")
. d = DogChild()
. d.bark()
. d.speak()
. d.eat()
Output:
dog barking
Animal Speaking
Eating bread...
Python provides us the flexibility to inherit multiple base classes in the child class.
Syntax
. class Base1:
. <class-suite>
.
. class Base2:
. <class-suite>
. .
. class BaseN:
. <class-suite>
.
Example
. class Calculation1:
. def Summation(self,a,b):
. return a+b;
. class Calculation2:
. def Multiplication(self,a,b):
. return a*b;
. class Derived(Calculation1,Calculation2):
. def Divide(self,a,b):
. return a/b;
. d = Derived()
. print(d.Summation(10,20))
. print(d.Multiplication(10,20))
. print(d.Divide(10,20))
Output:
30
200
0.5
Abstraction in Python
Abstraction is used to hide the internal functionality of the function from the users. The users only
interact with the basic implementation of the function, but inner working is hidden. User is familiar with
that "what function does" but they don't know "how it does."
In simple words, we all use the smartphone and very much familiar with its functions such as camera,
voice-recorder, call-dialing, etc., but we don't know how these operations are happening in the
background. Let's take another example - When we use the TV remote to increase the volume. We don't
know how pressing a key increases the volume of the TV. We only know to press the "+" button to
increase the volume.
A class that consists of one or more abstract method is called the abstract class. Abstract methods do not
contain their implementation. Abstract class can be inherited by the subclass and abstract method gets its
definition in the subclass. Abstraction classes are meant to be the blueprint of the other class. An abstract
class can be useful when we are designing large functions. An abstract class is also helpful to provide the
standard interface for different implementations of components. Python provides the abc module to use
the abstraction in the Python program. Let's see the following syntax.
In this tutorial, we are discussing Python file handling. Python supports the file-handling process. Till
now, we were taking the input from the console and writing it back to the console to interact with the user.
Users can easily handle the files, like read and write the files in Python. In another programming
language, the file-handling process is lengthy and complicated. But we know Python is an easy
programming language. So, like other things, file handling is also effortless and short in Python.
Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very
large, and only a limited amount of data can be displayed on the console since the memory is volatile, it
is impossible to recover the programmatically generated data again and again.
The file handling plays an important role when the data needs to be stored permanently into the file. A
file is a named location on disk to store related information. We can access the stored information (non-
volatile) after the program termination.
In Python, files are treated in two modes as text or binary. The file may be in the text or binary format,
and each line of a file is ended with the special character like a comma (,) or a newline character. Python
executes the code line by line. So, it works in one line and then asks the interpreter to start the new line
again. This is a continuous process in Python.
o Open a file
o Read or write - Performing operation
o Close the file
UNIT-V
Environment Setup
To build the real world applications, connecting with the databases is the necessity for the programming
languages. However, python allows us to connect our application to the databases like MySQL, SQLite,
MongoDB, and many others.
Install mysql.connector
To connect the python application with the MySQL database, we must import the mysql.connector
module in the program.
The mysql.connector is not a built-in module that comes with the python installation. We need to install it
to get it working.
. p install mysql-connector
Or follow the following steps.
. $ cd mysql-connector-python-8.0.13/
4. Run the file named setup.py with python (python3 in case you have also installed python 2) with the
parameter build.
Database Connection
In this section of the tutorial, we will discuss the steps to connect the python application to the database.
Pass the database details like HostName, username, and the database password in the method call. The
method returns the connection object.
Example
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")
.
. #printing the connection object
. print(myconn)
Output:
Example
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", databas
e = "mydb")
.
. #printing the connection object
. print(myconn)
Output:
. <my_cur> = conn.cursor()
Example
. import mysql.connector
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", databas
e = "mydb")
.
. #printing the connection object
. print(myconn)
.
. #creating the cursor object
. cur = myconn.cursor()
.
. print(cur)
Output:
We can get the list of all the databases by using the following MySQL query.
Example
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")
.
. #creating the cursor object
('EmployeeDB',)
('Test',)
('TestDB',)
('information_schema',)
('javatpoint',)
('javatpoint1',)
('mydb',)
('mysql',)
('performance_schema',)
('testDB',)
The new database can be created by using the following SQL query.
Example
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #creating a new database
. cur.execute("create database PythonDB2")
.
. #getting the list of all the databases which will now include the new database PythonDB
. dbs = cur.execute("show databases")
.
. except:
. myconn.rollback()
.
. for x in cur:
('EmployeeDB',)
('PythonDB',)
('Test',)
('TestDB',)
('anshika',)
('information_schema',)
('javatpoint',)
('javatpoint1',)
('mydb',)
('mydb1',)
('mysql',)
('performance_schema',)
('testDB',)
We can create the new table by using the CREATE TABLE statement of SQL. In our database
PythonDB, the table Employee will have the four columns, i.e., name, id, salary, and department_id
initially.
. > create table Employee (name varchar(20) not null, id int primary key, salary float not null, De
pt_Id int not null)
Example
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #Creating a table with name Employee having four columns i.e., name, id, salary, and departm
ent id
Now, we may check that the table Employee is present in the database.
Alter Table
Sometimes, we may forget to create some columns, or we may need to update the table schema. The alter
statement used to alter the table schema if required. Here, we will add the column branch_name to the
table Employee. The following SQL query is used for this purpose.
Example
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #adding a column branch name to the table Employee
. cur.execute("alter table Employee add branch_name varchar(20) not null")
. except:
. myconn.rollback()
.
. myconn.close()
We provide the actual values in the form of tuple in the execute() method of the cursor.
Example
. import mysql.connector
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
. #creating the cursor object
. cur = myconn.cursor()
. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s
)"
.
. #The row values are provided in the form of tuple
. val = ("John", 110, 25000.00, 201, "Newyork")
.
. try:
. #inserting the values into the table
. cur.execute(sql,val)
.
. #commit the transaction
. myconn.commit()
.
. except:
. myconn.rollback()
.
. print(cur.rowcount,"record inserted!")
. myconn.close()
Output:
1 record inserted!
Each element of the list is treated as one particular row, whereas each element of the tuple is treated as
one particular column value (attribute).
Example
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s
)"
. val = [("John", 102, 25000.00, 201, "Newyork"),("David",103,25000.00,202,"Port of spain"),("N
ick",104,90000.00,201,"Newyork")]
.
. try:
. #inserting the values into the table
. cur.executemany(sql,val)
.
. #commit the transaction
. myconn.commit()
. print(cur.rowcount,"records inserted!")
.
. except:
. myconn.rollback()
.
. myconn.close()
Output:
Row ID
In SQL, a particular row is represented by an insertion id which is known as row id. We can get the last
inserted row id by using the attribute lastrowid of the cursor object.
Example
. import mysql.connector
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
. #creating the cursor object
. cur = myconn.cursor()
.
. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s
)"
.
. val = ("Mike",105,28000,202,"Guyana")
.
. try:
. #inserting the values into the table
. cur.execute(sql,val)
.
. #commit the transaction
. myconn.commit()
.
. #getting rowid
. print(cur.rowcount,"record inserted! id:",cur.lastrowid)
.
. except:
. myconn.rollback()
.
Python provides the fetchall() method returns the data stored inside the table in the form of rows. We can
iterate the result to get the individual rows.
In this section of the tutorial, we will extract the data from the database by using the python script. We
will also format the output to print it on the console.
Example
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #Reading the Employee data
. cur.execute("select * from Employee")
.
. #fetching the rows from the cursor object
. result = cur.fetchall()
. #printing the result
.
. for x in result:
. print(x);
. except:
. myconn.rollback()
.
. myconn.close()
Output:
Example
. import mysql.connector
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
. #creating the cursor object
. cur = myconn.cursor()
. try:
. #Reading the Employee data
. cur.execute("select name, id, salary from Employee")
.
. #fetching the rows from the cursor object
. result = cur.fetchall()
. #printing the result
. for x in result:
. print(x);
. except:
. myconn.rollback()
. myconn.close()
Output:
Example
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #Reading the Employee data
Example
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
.
. #Reading the Employee data
. cur.execute("select name, id, salary from Employee")
.
. #fetching the rows from the cursor object
. result = cur.fetchall()
.
. print("Name id Salary");
. for row in result:
. print("%s %d %d"%(row[0],row[1],row[2]))
. except:
. myconn.rollback()
.
. myconn.close()
Output:
We can restrict the result produced by the select statement by using the where clause. This will extract
only those columns which satisfy the where condition.
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #Reading the Employee data
. cur.execute("select name, id, salary from Employee where name like 'J%'")
.
. #fetching the rows from the cursor object
. result = cur.fetchall()
.
. print("Name id Salary");
.
. for row in result:
. print("%s %d %d"%(row[0],row[1],row[2]))
. except:
. myconn.rollback()
.
. myconn.close()
Output:
Name id Salary
John 101 25000
John 102 25000
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #Reading the Employee data
. cur.execute("select name, id, salary from Employee where id in (101,102,103)")
.
. #fetching the rows from the cursor object
. result = cur.fetchall()
.
. print("Name id Salary");
.
. for row in result:
. print("%s %d %d"%(row[0],row[1],row[2]))
. except:
. myconn.rollback()
.
. myconn.close()
Output:
Name id Salary
John 101 25000
John 102 25000
David 103 2500
Example
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #Reading the Employee data
Name id Salary
David 103 25000
John 101 25000
John 102 25000
Mike 105 28000
Nick 104 90000
Order by DESC
This orders the result in the decreasing order of a particular column.
Example
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #Reading the Employee data
. cur.execute("select name, id, salary from Employee order by name desc")
.
. #fetching the rows from the cursor object
. result = cur.fetchall()
.
. #printing the result
. print("Name id Salary");
. for row in result:
. print("%s %d %d"%(row[0],row[1],row[2]))
.
. except:
Name id Salary
Nick 104 90000
Mike 105 28000
John 101 25000
John 102 25000
David 103 25000
Update Operation
The UPDATE-SET statement is used to update any column inside the table. The following SQL query is
used to update a column.
Example
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #updating the name of the employee whose id is 110
. cur.execute("update Employee set name = 'alex' where id = 110")
. myconn.commit()
. except:
.
. myconn.rollback()
.
. myconn.close()
The following SQL query is used to delete the employee detail whose id is 110 from the table.
Example
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #Deleting the employee details whose id is 110
. cur.execute("delete from Employee where id = 110")
. myconn.commit()
. except:
.
. myconn.rollback()
.
. myconn.close()
Join Operation
We can combine the columns from two or more tables by using some common column among them by
using the join statement.
We have only one table in our database, let's create one more table Departments with two columns
department_id and department_name.
As we have created a new table Departments as shown in the above image. However, we haven't yet
inserted any value inside it.
Let's insert some Departments ids and departments names so that we can map this to our Employee table.
Now, let's create a python script that joins the two tables on the common column, i.e., dept_id.
Example
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #joining the two tables on departments_id
Right Join
Right join shows all the columns of the right-hand side table as we have two tables in the database
PythonDB, i.e., Departments and Employee. We do not have any Employee in the table who is not
working for any department (Employee for which department id is null). However, to understand the
concept of right join let's create the one.
Now, we have an employee in the Employee table whose department id is not present in the Departments
table. Let's perform the right join on the two tables now.
Example
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #joining the two tables on departments_id
Example
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #joining the two tables on departments_id
. result = cur.execute("select Employee.id, Employee.name, Employee.salary, Departments.Dep
t_id, Departments.Dept_Name from Departments left join Employee on Departments.Dept_id = Employe
e.Dept_id")
. print("ID Name Salary Dept_Id Dept_Name")
. for row in cur:
. print(row[0]," ", row[1]," ",row[2]," ",row[3]," ",row[4])
.
. except:
. myconn.rollback()
Performing Transactions
Transactions ensure the data consistency of the database. We have to make sure that more than one
applications must not modify the records while performing the database operations. The transactions
have the following properties.
1. Atomicity
Either the transaction completes, or nothing happens. If a transaction contains 4 queries then all
these queries must be executed, or none of them must be executed.
2. Consistency
The database must be consistent before the transaction starts and the database must also be
consistent after the transaction is completed.
3. Isolation
Intermediate results of a transaction are not visible outside the current transaction.
4. Durability
Once a transaction was committed, the effects are persistent, even after a system failure.
. Conn.rollback()
. conn.close()
In the following example, we are deleting all the employees who are working for the CS department.
Example
. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. cur.execute("delete from Employee where Dept_id = 201")
. myconn.commit()
. print("Deleted !")
. except:
. print("Can't delete !")
. myconn.rollback()
.
. myconn.close()
Output:Deleted !