Python Tutorial
Python Tutorial
Python is a simple, general purpose, high level, and object-oriented programming language.
Python is an interpreted scripting language also. Guido Van Rossum is known as the founder of
Python programming.
What is Python
Python is a general purpose, dynamic, high-level, and interpreted programming language. It
supports Object Oriented programming approach to develop applications. It is simple and easy to
learn and provides lots of high-level data structures.
Python is easy to learn yet powerful and versatile scripting language, which makes it attractive
for Application Development.
Python's syntax and dynamic typing with its interpreted nature make it an ideal language for
scripting and rapid application development.
Python is not intended to work in a particular area, such as web programming. That is why it is
known as multipurpose programming language because it can be used with web, enterprise, 3D
CAD, etc.
We don't need to use data types to declare variable because it is dynamically typed so we can
write a=10 to assign an integer value in an integer variable.
Python makes the development and debugging fast because there is no compilation step included
in Python development, and edit-test-debug cycle is very fast.
Python History
Python was invented by Guido van Rossum in 1991 at CWI in Netherland. The idea of Python
programming language has taken from the ABC programming language or we can say that ABC
is a predecessor of Python language.
There is also a fact behind the choosing name Python. Guido van Rossum was a fan of the
popular BBC comedy show of that time, "Monty Python's Flying Circus". So he decided to
pick the name Python for his newly created programming language.
Python has the vast community across the world and releases its version within the short period.
Why learn Python?
Python provides many useful features to the programmer. These features make it most popular
and widely used language. We have listed below few-essential feature of Python.
Data Science
Data Mining
Desktop Applications
Console-based Applications
Mobile Applications
Software Development
Artificial Intelligence
Web Applications
Enterprise Applications
3D CAD Applications
Machine Learning
Computer Vision or Image Processing Applications.
Speech Recognitions
In the above example, the statements that are same level to right belong to the function.
Generally, we can use four whitespaces to define indentation.
1. public class HelloWorld {
2. public static void main(String[] args){
3. // Prints "Hello, World" to the terminal window.
4. System.out.println("Hello World");
5. }
6. }
1. print("Hello World")
Both programs will print the same result, but it takes only one statement without using a
semicolon or curly braces in Python.
Unlike the other programming languages, Python print() function is most unique and versatile
function.
1. print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
objects - An object is nothing but a statement that to be printed. The * sign represents
that there can be multiple statements.
sep - The sep parameter separates the print values. Default values is ' '.
end - The end is printed at last in the statement.
file - It must be an object with a write(string) method.
flush - The stream or file is forcibly flushed if it is true. By default, its value is false.
1. print("Welcome to javaTpoint.")
2.
3. a = 10
4. # Two objects are passed in print() function
5. print("a =", a)
6.
7. b = a
8. # Three objects are passed in print function
9. print('a =', a, '= b')
Output:
Welcome to javaTpoint.
a = 10
a = 10 = b
As we can see in the above output, the multiple objects can be printed in the single print()
statement. We just need to use comma (,) to separate with each other.
Example - 2: Using sep and end argument
1. a = 10
2. print("a =", a, sep='dddd', end='\n\n\n')
3. print("a =", a, sep='0', end='$$$$$')
Output:
a =dddd10
a =010$$$$$
In the first print() statement, we use the sep and end arguments. The given object is printed just
after the sep values. The value of end parameter printed at the last of given object. As we can see
that, the second print() function printed the result after the three black lines.
Example -
1. name = input("Enter a name of student:")
2. print("The student name is: ", name)
Output:
By default, the input() function takes the string input but what if we want to take other data
types as an input.
If we want to take input as an integer number, we need to typecast the input() function into an
integer.
For example -
Example -
1. a = int(input("Enter first number: "))
2. b = int(input("Enter second number: "))
3.
4. print(a+b)
Output:
Python Operators
Operators are the symbols which perform various operations on Python objects. Python operators
are the most essential to work with the Python data types. In addition, Python also provides
identify membership and bitwise operators. We will learn all these operators with the suitable
example in following tutorial.
Python Operators
Python Loops
Sometimes we may need to alter the flow of the program. The execution of a specific code may
need to be repeated several numbers of times. For this purpose, the programming languages
provide various types of loops capable of repeating some specific code several times. Consider
the following tutorial to understand the statements in detail.
Python Loops
Python For Loop
Python While Loop
Python List
Python list holds the ordered collection of items. We can store a sequence of items in a list.
Python list is mutable which means it can be modified after its creation. The items of lists are
enclosed within the square bracket [] and separated by the comma. Let's see the example of list.
1. L1 = ["John", 102, "USA"]
2. L2 = [1, 2, 3, 4, 5, 6]
If we try to print the type of L1, L2, and L3 using type() function then it will come out to be a
list.
1. print(type(L1))
2. print(type(L2))
Output:
<class 'list'>
<class 'list'>
Python List
Python List Functions
Python Tuple
Python Tuple is used to store the sequence of immutable Python objects. The tuple is similar to
lists since the value of the items stored in the list can be changed, whereas the tuple is
immutable, and the value of the items stored in the tuple cannot be changed.
Example -
1. tup = ("Apple", "Mango" , "Orange" , "Banana")
2. print(type(tup))
3. print(tup)
Output:
<class 'tuple'>
('Apple', 'Mango', 'Orange', 'Banana')
Example -
1. tup = ("Apple", "Mango" , "Orange" , "Banana")
2.
3. tup[2] = "Papaya"
4. print(tup)
Output:
The above program throws an error because tuples are immutable type. To learn more about
tuple, visit the Python Tuples.
Python Tuple
Python String
Example -
1. # Creating string using double quotes
2. str1 = "Hi Python"
3. print(str1)
4. # Creating string using single quotes
5. str1 = 'Hi Python'
6. print(str1)
7. # Creating string using triple quotes
8. str1 = '''Hi Python'''
9. print(str1)
Output:
Hi Python
Hi Python
Hi Python
Python doesn't support the character data-type. A single character written as 'p' is treated as a
string of length 1.
Stings are also immutable. We can't change after it is declared. To learn more about the string,
visit the following tutorial.
Python Strings
Python String Method
Dictionaries
Python Dictionary is a most efficient data structure and used to store the large amount of data. It
stores the data in the key-value pair format. Each value is stored corresponding to its key.
Keys must be a unique and value can be any type such as integer, list, tuple, etc.
It is a mutable type; we can reassign after its creation. Below is the example of creating
dictionary in Python.
Example -
1. employee = {"Name": "John", "Age": 29, "salary":250000,"Company":"GOOGLE"}
2. print(type(employee))
3. print("printing Employee data .... ")
4. print(employee)
Output:
<class 'dict'>
Printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 250000, 'Company': 'GOOGLE'}
The empty curly braces {} are used to create empty dictionary. To learn more, visit the complete
tutorial of the dictionary.
Python Dictionary
Python Dictionary Methods
Python Sets
A Python set is a collection of unordered elements. Each element in set must be unique and
immutable. Sets are mutable which means we can modify anytime throughout the program. Let's
understand the example of creating set in Python.
Example -
1. # Creating Set
2. Month = {"January", "February", "March", "April", "May", "June", "July"}
3. print(Month)
4. print(type(Month))
Output:
{'March', 'July', 'April', 'May', 'June', 'February', 'January'}
<class 'set'>
To get the more information about sets, visit the following resources.
Python Sets
Python Set Methods
Python Function
Python map() Function
Python filter() Function
Python reduce() Function
Python functool Module
Python Lambda Function
Python Modules
Python modules are the program files that contain a Python code or functions. There are two
types of module in the Python - User-define modules and built-in modules. A module that the
user defines, or we can say that our Python code saved with .py extension, is treated as a user-
define module.
Built-in modules are predefined modules of Python. To use the functionality of the modules, we
need to import them into our current working program.
Python Modules
Python Exceptions
An exception can be defined as an unusual condition in a program resulting in the interruption in
the flow of the program.
Whenever an exception occurs, the program stops the execution, and thus the further code is not
executed. Therefore, an exception is the run-time errors that are unable to handle to Python
script. An exception is a Python object that represents an error.
Python Exceptions
Python CSV
A csv stands for "comma separated values", which is defined as a simple file format that uses
specific structuring to arrange tabular data. It stores tabular data such as spreadsheet or database
in plain text and has a common format for data interchange. A csv file opens into the excel sheet,
and the rows and columns data define the standard format. Visit the following tutorial to learn
the CSV module in detail.
The built-in classes define many magic methods. The dir() function can be used to see the
number of magic methods inherited by a class. It has two prefixes and suffix underscores in the
method name.
Classes and Objects - Python classes are the blueprint of the object. An object is a
collection of data and method that act on the data.
Inheritance - An inheritance is a technique where one class inherits the properties of
other classes.
Constructor - Python provides a special method __init__() which is known as a
constructor. This method is automatically called when an object is instantiated.
Data Member - A variable that holds data associated with a class and its objects.
Python Iterator
An iterator is simply an object that can be iterated upon. It returns one object at a time. It can be
implemented using the two special methods, __iter__() and __next__().
To learn more about the iterators visit our Python Iterators tutorial.
Python Generators
The Generators are an easiest way of creating Iterators. To learn more about, visit our Python
Generators tutorial.
Python Decorators
These are used to modify the behavior of the function. Decorators provide the flexibility to wrap
another function to expand the working of wrapped function, without permanently modifying it.
Python MySQL
Environment Setup
Database Connection
Creating Tables
Insert Operation
Read Operation
Update Operation
Join Operation
Performing Transactions
Python MongoDB
Python MongoDB
Python SQLite
Python SQLite
Python Features
Python provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming, procedural programming
approaches and provides dynamic memory allocation. We have listed below a few essential
features.
2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello world
program you simply type print("Hello World"). It will take only one line to execute, while Java
or C takes multiple lines.
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a time.
The advantage of being interpreted language, it makes debugging easy and portable.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh,
etc. So, we can say that Python is a portable language. It enables programmers to develop the
software for several competing platforms by writing a program only once.
Python is freely available for everyone. It is freely available on its official website
www.python.org. It has a large community across the world that is dedicatedly working towards
make new python modules and functions. Anyone can contribute to the Python community. The
open-source means, "Anyone can download its source code without paying any penny."
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into
existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented
procedure helps to programmer to write reusable code and develop applications in less code.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can be
used further in our Python code. It converts the program into byte code, and any platform can use
that byte code.
It provides a vast range of libraries for the various fields such as machine learning, web
developer, and also for the scripting. There are various machine learning libraries, such as
Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular
framework for Python web development.
Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy
are the libraries which are used for developing the web application.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by
line like C,C++ Java. It makes easy to debug the code.
11. Embeddable
The code of the other programming language can use in the Python source code. We can use
Python source code in another programming language as well. It can embed other language into
our code.
In Python, we don't need to specify the data-type of the variable. When we assign some value to
the variable, it automatically allocates the memory to the variable at run time. Suppose we are
assigned integer value 15 to x, then we don't need to write int x = 15. Just write x = 15.
The most common question asked by the beginners - "What is the best way to learn Python"?
It is the initial and relevant question because first step in learning any programming language is
to know how to learn.
The proper way of learning will help us to learn fast and become a good Python developer.
In this section, we will discuss various tips that we should keep in mind while learning Python.
The goal should be clear before learning the Python. Python is an easy, a vast language as well.
It includes numbers of libraries, modules, in-built functions and data structures. If the goal is
unclear then it will be a boring and monotonous journey of learning Python. Without any clear
goal, you perhaps won't make it done.
So, first figure out the motivation behind learning, which can anything be such as knowing
something new, develop projects using Python, switch to Python, etc. Below are the general
areas where Python is widely used. Pick any of them.
Data Analysis and Processing
Artificial Intelligence
Games
Hardware/Sensor/Robots
Desktop Applications
Choose any one or two areas according to your interest and start the journey towards learning
Python.
It is the most essential and basic step to learn the syntax of the Python programming language.
We have to learn the basic syntax before dive deeper into learning it. As we have discussed in
our earlier tutorial, Python is easy to learn and has a simple syntax. It doesn't use semicolon and
brackets. Its syntax is like the English language.
So it will take minimum amount of time to learning its syntax. Once we get its syntax properly,
further learning will be easier and quicker getting to work on projects.
Note - Learn Python 3, not Python 2.7, because the industry no longer uses it. Our Python tutorial is
based on its latest version Python 3.
Writing the code is the most effective and robust way to learn Python. First, try to write code on
paper and run in mind (Dry Run) then move to the system. Writing code on paper will help us
get familiar quickly with the syntax and the concept store in the deep memory. While writing the
code, try to use proper functions and suitable variables names.
There are many editors available for Python programming which highlights the syntax related
issue automatically. So we don't need to pay lot of attention of these mistakes.
4. Keep Practicing
The next important step is to do the practice. It needs to implementing the Python concepts
through the code. We should be consistence to our daily coding practice.
Consistency is the key of success in any aspect of life not only in programming. Writing code
daily will help to develop muscle memory.
We can do the problem exercise of related concepts or solve at least 2 or 3 problems of Python. It
may seem hard but muscle memory plays large part in programing. It will take us ahead from
those who believe only the reading concept of Python is sufficient.
Maintain own notes are also helped to learn fast. A study published in Psychological Science that
-
The students who were taking longhand notes in the studies were forced to be more selective —
because you can't write as fast as you can type.
Coding seems to be solitary activity, but we can enhance our skills by interacting with the others.
We should discuss our doubts to the expert or friends who are learning Python. This habit will
help to get additional information, tips and tricks, and solution of coding problems. One of the
best advantages of Python, it has a great community. Therefore, we can also learn from
passionate Python enthusiasts.
7. Do small Projects
After understanding Python's basic concept, a beginner should try to work on small projects. It
will help to understand Python more deeply and become more component in it. Theoretical
knowledge is not enough to get command over the Python language. These projects can be
anything as long as they teach you something. You can start with the small projects such as
calculator app, a tic-toc-toe game, an alarm clock app, a to-do list, student or customer
management system, etc.
Once you get handy with a small project, you can easily shift toward your interesting domain
(Machine Learning, Web Development, etc.).
8. Teach Others
There is a famous saying that "If you want to learn something then you should teach other".
It is also true in case of learning Python. Share your information to other students via creating
blog posts, recording videos or taking classes in local training center. It will help us to enhance
the understanding of Python and explore the unseen loopholes in your knowledge. If you don't
want to do all these, join the online forum and post your answers on Python related questions.
Python consists of vast libraries and various frameworks. After getting familiar with Python's
basic concepts, the next step is to explore the Python libraries. Libraries are essential to work
with the domain specific projects. In the following section, we describe the brief introduction of
the main libraries.
TensorFlow - It is an artificial intelligence library which allows us to create large scale AI based
projects.
Django - It is an open source framework that allows us to develop web applications. It is easy,
flexible, and simple to manage.
Flask - It is also an open source web framework. It is used to develop lightweight web
applications.
Pandas - It is a Python library which is used to perform scientific computations.
Keras - It is an open source library, which is used to work around the neural network.
There are many libraries in Python. Above, we have mentioned a few of them.
As we know, Python is an open source language that means it is freely available for everyone.
We can also contribute to Python online community to enhance our knowledge. Contributing to
open source projects is the best way to explore own knowledge. We also receive the feedback,
comments or suggestions for work that we submitted. The feedback will enable the best practices
for Python programming and help us to become a good Python developer.
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. The usage of Python as follows.
Desktop Applications
Web Applications
Data Science
Artificial Intelligence
Machine Learning
Scientific Computing
Robotics
Internet of Things (IoT)
Gaming
Mobile Apps
Data Analysis and Preprocessing
Python Applications
Python is known for its general-purpose nature that makes it applicable in almost every domain
of software development. Python makes its presence in every emerging field. It is the fastest-
growing programming language and can develop any application.
We can use Python to develop web applications. It provides libraries to handle internet protocols
such as HTML and XML, JSON, Email processing, request, beautifulSoup, Feedparser, etc. One
of Python web-framework named Django is used on Instagram. Python provides many useful
frameworks, and these are given below:
The GUI stands for the Graphical User Interface, which provides a smooth interaction to any
application. Python provides a Tk GUI library to develop a user interface. Some popular GUI
libraries are given below.
Tkinter or Tk
wxWidgetM
Kivy (used for writing multitouch applications )
PyQt or Pyside
3) Console-based Application
Console-based applications run from the command-line or shell. These applications are computer
program which are used commands to execute. This kind of application was more popular in the
old generation of computers. Python can develop this kind of application very effectively. It is
famous for having REPL, which means the Read-Eval-Print Loop that makes it the most
suitable language for the command-line applications.
Python provides many free library or module which helps to build the command-line apps. The
necessary IO libraries are used to read and write. It helps to parse argument and create console
help text out-of-the-box. There are also advance libraries that can develop independent console
apps.
4) Software Development
Python is useful for the software development process. It works as a support language and can be
used to build control and management, testing, etc.
This is the era of Artificial intelligence where the machine can perform the task the same as the
human. Python language is the most suitable language for Artificial intelligence or machine
learning. It consists of many scientific and mathematical libraries, which makes easy to solve
complex calculations.
SciPy
Scikit-learn
NumPy
Pandas
Matplotlib
6) Business Applications
Business Applications differ from standard applications. E-commerce and ERP are an example
of a business application. This kind of application requires extensively, scalability and
readability, and Python provides all these features.
Oddo is an example of the all-in-one Python-based application which offers a range of business
applications. Python provides a Tryton platform which is used to develop the business
application.
Python is flexible to perform multiple tasks and can be used to create multimedia applications.
Some multimedia applications which are made by using Python are TimPlayer, cplay, etc. The
few multimedia libraries are given below.
Gstreamer
Pyglet
QT Phonon
8) 3D CAD Applications
The CAD (Computer-aided design) is used to design engineering related architecture. It is used
to develop the 3D representation of a part of a system. Python can create a 3D CAD application
by using the following functionalities.
Fandango (Popular )
CAMVOX
HeeksCNC
AnyCAD
RCAM
9) Enterprise Applications
Python can be used to create applications that can be used within an Enterprise or an
Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.
Python contains many libraries that are used to work with the image. The image can be
manipulated according to our requirements. Some libraries of image processing are given below.
OpenCV
Pillow
SimpleITK
In this topic, we have described all types of applications where Python plays an essential role in
the development of these applications. In the next tutorial, we will learn more concepts about
Python.
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.
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.
1. 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.
The output will be shown as follows.
Step - 4: Apart from that, we can also run the file using the operating system terminal. But, we
should be aware of the path of the directory where we have saved our 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:
1. name = "Andrew Venis"
2. branch = "Computer Science"
3. age = "25"
4. print("My name is: ", name, )
5. print("My age is: ", age)
Script File:
The script mode has few advantages and disadvantages as well. Let's understand the following
advantages of running code in script mode.
We have to save the code every time if we make any change in the code.
It can be tedious when we run a single or a few lines of 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. list1 = [1, 2, 3, 4, 5]
2. for i in list1:
3. print(i)
4. if i==4:
5. break
6. print("End of for loop")
Output:
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.
1. name = "Thomas" # Assigning string value to the name variable
1. Fees = 10000 # defining course fees is 10000
2. Fees = 20000 # defining course fees is 20000
It is good idea to add code in any line of the code section of code whose purpose is not obvious.
This is a best practice to learn while doing the coding.
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.
1. # defining the marks of a student
2. Marks = 90
We can also write a comment next to a code statement. Consider the following example.
1. Name = "James" # the name of a student is James
2. Marks = 90 # defining student's marks
3. Branch = "Computer Science" # defining student branch
Multi-Line Comments - Python doesn't have explicit support for multi-line comments but we
can use hash # character to the multiple lines. For example -
1. # we are defining for loop
2. # To iterate the given list.
3. # run this code.
1. " " "
2. This is an example
3. Of multi-line comment
4. Using triple-quotes
5. " " "
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.
A variable name must start with either an English letter or underscore (_).
A variable name cannot start with the number.
Special characters are not allowed in the variable name.
The variable's name is case sensitive.
Example -
1. number = 10
2. print(num)
3.
4. _a = 100
5. print(_a)
6.
7. x_y = 1000
8. print(x_y)
Python Variables
Variable is a name that is used to refer to memory location. Python variable is also known as an
identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a infer language and
smart enough to get variable type.
Variable names can be a group of both the letters and digits, but they have to begin with a letter
or an underscore.
It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two
different variables.
Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals used in the
program. The rules to name an identifier are given below.
Python does not bind us to declare a variable before using it in the application. It allows us to
create a variable at the required time.
We don't need to declare explicitly variable in Python. When we assign any value to the variable,
that variable is declared automatically.
Object References
It is necessary to understand how the Python interpreter works when we declare a variable. The
process of treating variables is somewhat different from many other programming languages.
Python is the highly object-oriented programming language; that's why every data item belongs
to a specific type of class. Consider the following example.
1. print("John")
Output:
John
The Python object creates an integer object and displays it to the console. In the above print
statement, we have created a string object. Let's check the type of it using the Python built-in
type() function.
1. type("John")
Output:
<class 'str'>
In Python, variables are a symbolic name that is a reference or pointer to an object. The variables
are used to denote objects by that name.
1. 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
In Python, every created object identifies uniquely in Python. Python provides the guaranteed
that no two objects will have the same identifier. The built-in id() function, is used to identify the
object identifier. Consider the following example.
1. a = 50
2. b = a
3. print(id(a))
4. print(id(b))
5. # Reassigned variable a
6. a = 500
7. print(id(a))
Output:
140734982691168
140734982691168
2822056960944
We assigned the b = a, a and b both point to the same object. When we checked by the id()
function it returned the same number. We reassign a to 500; then it referred to the new object
identifier.
Variable Names
We have already discussed how to declare the valid variable. Variable names can be any length
can have uppercase, lowercase (A to Z, a to z), the digit (0-9), and underscore character(_).
Consider the following example of valid variables names.
1. name = "Devansh"
2. age = 20
3. marks = 80.50
4.
5. print(name)
6. print(age)
7. print(marks)
Output:
Devansh
20
80.5
1. name = "A"
2. Name = "B"
3. naMe = "C"
4. NAME = "D"
5. n_a_m_e = "E"
6. _name = "F"
7. name_ = "G"
8. _name_ = "H"
9. na56me = "I"
10.
11. print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name, na56me)
Output:
A B C D E D E F G F I
In the above example, we have declared a few valid variable names such as name, _name_ , etc.
But it is not recommended because when we try to read code, it may create confusion. The
variable name should be descriptive to make code more readable.
Camel Case - In the camel case, each word or abbreviation in the middle of begins with a capital
letter. There is no intervention of whitespace. For example - nameOfStudent, valueOfVaraible,
etc.
Pascal Case - It is the same as the Camel Case, but here the first word is also capital. For
example - NameOfStudent, etc.
Snake Case - In the snake case, Words are separated by the underscore. For example -
name_of_student, etc.
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is also
known as multiple assignments.
We can apply multiple assignments in two ways, either by assigning a single value to multiple
variables or assigning multiple values to multiple variables. Consider the following example.
Eg:
1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)
Output:
50
50
50
Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
5
10
15
There are two types of variables in Python - Local variable and Global variable. Let's understand
the following variables.
Local Variable
Local variables are the variables that declared inside the function and have scope within the
function. Let's understand the following example.
Example -
1. # Declaring a function
2. def add():
3. # Defining local variables. They has scope only within a function
4. a = 20
5. b = 30
6. c = a + b
7. print("The sum is:", c)
8.
9. # Calling a function
10. add()
Output:
Explanation:
In the above code, we declared a function named add() and assigned a few variables within the
function. These variables will be referred to as the local variables which have scope only inside
the function. If we try to use them outside the function, we get a following error.
1. add()
2. # Accessing local variable outside the function
3. print(a)
Output:
We tried to use local variable outside their scope; it threw the NameError.
Global Variables
Global variables can be used throughout the program, and its scope is in the entire program. We
can use global variables inside or outside the function.
A variable declared outside the function is the global variable by default. Python provides the
global keyword to use global variable inside the function. If we don't use the global keyword,
the function treats it as a local variable. Let's understand the following example.
Example -
1. # Declare a variable and initialize it
2. x = 101
3.
4. # Global variable in function
5. def mainFunction():
6. # printing a global variable
7. global x
8. print(x)
9. # modifying a global variable
10. x = 'Welcome To Javatpoint'
11. print(x)
12.
13. mainFunction()
14. print(x)
Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Explanation:
In the above code, we declare a global variable x and assign a value to it. Next, we defined a
function and accessed the declared variable using the global keyword inside the function. Now
we can modify its value. Then, we assigned a new string value to the variable x.
Now, we called the function and proceeded to print x. It printed the as newly assigned value of x.
Delete a variable
We can delete the variable using the del keyword. The syntax is given below.
Syntax -
1. 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 -
1. # Assigning a value to x
2. x = 6
3. print(x)
4. # deleting a variable.
5. del x
6. 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
Unlike the other programming languages, Python doesn't have long int or float data types. It
treats all integer values as an int data type. Here, the question arises. What is the maximum
possible value can hold by the variable in Python? Consider the following example.
Example -
1. # A Python program to display that we can store
2. # large numbers in Python
3.
4. a = 10000000000000000000000000000000000000000000
5. a = a + 1
6. print(type(a))
7. print (a)
Output:
<class 'int'>
10000000000000000000000000000000000000000001
As we can see in the above example, we assigned a large integer value to variable x and checked
its type. It printed class <int> not long int. Hence, there is no limitation number by bits and we
can expand to the limit of our memory.
Python doesn't have any special data type to store larger numbers.
We can print multiple variables within the single print statement. Below are the example of
single and multiple printing values.
1. # printing single value
2. a = 5
3. print(a)
4. print((a))
Output:
5
5
1. a = 5
2. b = 6
3. # printing multiple variables
4. print(a,b)
5. # separate the variables by the comma
6. Print(1, 2, 3, 4, 5, 6, 7, 8)
Output:
5 6
1 2 3 4 5 6 7 8
Basic Fundamentals:
This section contains the fundamentals of Python, such as:
ii) Comments
a)Tokens:
The tokens can be defined as a punctuator mark, reserved words, and each word in a statement.
The token is the smallest unit inside the given program.
Keywords.
Identifiers.
Literals.
Operators.
The variable a holds integer value five and we did not define its type. Python interpreter will
automatically interpret variables a as an integer type.
Python enables us to check the type of the variable used in the program. Python provides us the
type() function, which returns the type of the variable passed.
Consider the following example to define the values of different data types and checking its type.
1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
Standard data types
A variable can hold different types of values. For example, a person's name must be stored as a
string whereas its id must be stored as an integer.
Python provides various standard data types that define the storage method on each of them. The
data types defined in Python are given below.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
In this section of the tutorial, we will give a brief introduction of the above data-types. We will
discuss each one of them in detail later in this tutorial.
Numbers
Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type. Python provides the type() function to know the data-type of the variable.
Similarly, the isinstance() function is used to check an object belongs to a particular class.
Python creates Number objects when a number is assigned to a variable. For example;
1. a = 5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))
Output:
1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has no
restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is accurate upto
15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote the real
and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j, etc.
Sequence Type
String
The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.
String handling in Python is a straightforward task since Python provides built-in functions and
operators to perform operations in the string.
In the case of string handling, the operator + is used to concatenate two strings as the operation
"hello"+" python" returns "hello python".
The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python
Python'.
Example - 1
1. str = "string using double quotes"
2. print(str)
3. s = '''''A multiline
4. string'''
5. print(s)
Output:
1. str1 = 'hello javatpoint' #string str1
2. str2 = ' how are you' #string str2
3. print (str1[0:2]) #printing first two character using slice operator
4. print (str1[4]) #printing 4th character of the string
5. print (str1*2) #printing the string twice
6. print (str1 + str2) #printing the concatenation of str1 and str2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
List
Python Lists are similar to arrays in C. However, the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+) and
repetition operator (*) works with the list in the same way as they were working with the strings.
1. list1 = [1, "hi", "Python", 2]
2. #Checking type of given list
3. print(type(list1))
4.
5. #Printing the list1
6. print (list1)
7.
8. # List slicing
9. print (list1[3:])
10.
11. # List slicing
12. print (list1[0:2])
13.
14. # List Concatenation using + operator
15. print (list1 + list1)
16.
17. # List repetation using * operator
18. print (list1 * 3)
Output:
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and enclosed
in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.
1. tup = ("hi", "Python", 2)
2. # Checking type of tup
3. print (type(tup))
4.
5. #Printing the tuple
6. print (tup)
7.
8. # Tuple slicing
9. print (tup[1:])
10. print (tup[0:1])
11.
12. # Tuple concatenation using + operator
13. print (tup + tup)
14.
15. # Tuple repatation using * operator
16. print (tup * 3)
17.
18. # Adding value to tup. It will throw an error.
19. t[2] = "hi"
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.
1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
2.
3. # Printing dictionary
4. print (d)
5.
6. # Accesing value using keys
7. print("1st name is "+d[1])
8. print("2nd name is "+ d[4])
9.
10. print (d.keys())
11. print (d.values())
Output:
Boolean
Boolean type provides two built-in values, True and False. These values are used to determine
the given statement true or false. It denotes by the class bool. True can be represented by any
non-zero value or 'T' whereas false can be represented by the 0 or 'F'. Consider the following
example.
1. # Python program to check the boolean type
2. print(type(True))
3. print(type(False))
4. print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after
creation), and has unique elements. In set, the order of the elements is undefined; it may return
the changed sequence of the element. The set is created by using a built-in function set(), or a
sequence of elements is passed in the curly braces and separated by the comma. It can contain
various types of values. Consider the following example.
1. # Creating Empty set
2. set1 = set()
3.
4. set2 = {'James', 2, 3,'Python'}
5.
6. #Printing Set value
7. print(set2)
8.
9. # Adding element to the set
10.
11. set2.add(10)
12. print(set2)
13.
14. #Removing element from the set
15. set2.remove(2)
16. print(set2)
Python Keywords
Python Keywords are special reserved words that convey a special meaning to the
compiler/interpreter. Each keyword has a special meaning and a specific operation. These
keywords can't be used as a variable. Following is the List of Python Keywords.
1. True - It represents the Boolean true, if the given condition is true, then it returns "True". Non-
zero values are treated as true.
2. False - It represents the Boolean false; if the given condition is false, then it returns "False". Zero
value is treated as false
3. None - It denotes the null value or void. An empty list or Zero can't be treated as None.
4. and - It is a logical operator. It is used to check the multiple conditions. It returns true if both
conditions are true. Consider the following truth table.
A B A and B
5. or - It is a logical operator in Python. It returns true if one of the conditions is true. Consider
the following truth table.
A B A and B
6. not - It is a logical operator and inverts the truth value. Consider the following truth table.
A Not A
True False
False True
7. assert - This keyword is used as the debugging tool in Python. It checks the correctness of the
code. It raises an AssertionError if found any error in the code and also prints the message with
an error.
Example:
1. a = 10
2. b = 0
3. print('a is dividing by Zero')
4. assert b != 0
5. print(a / b)
Output:
a is dividing by Zero
Runtime Exception:
Traceback (most recent call last):
File "/home/40545678b342ce3b70beb1224bed345f.py", line 4, in
assert b != 0, "Divide by 0 error"
AssertionError: Divide by 0 error
8. def - This keyword is used to declare the function in Python. If followed by the function name.
1. def my_func(a,b):
2. c = a+b
3. print(c)
4. my_func(10,20)
Output:
30
9. class - It is used to represents the class in Python. The class is the blueprint of the objects. It is
the collection of the variable and methods. Consider the following class.
1. class Myclass:
2. #Variables……..
3. def function_name(self):
4. #statements………
10. continue - It is used to stop the execution of the current iteration. Consider the following
example.
1. a = 0
2. while a < 4:
3. a += 1
4. if a == 2:
5. continue
6. print(a)
Output:
1
3
4
11. break - It is used to terminate the loop execution and control transfer to the end of the loop.
Consider the following example.
Example
1. for i in range(5):
2. if(i==3):
3. break
4. print(i)
5. print("End of execution")
Output:
0
1
2
End of execution
12. If - It is used to represent the conditional statement. The execution of a particular block is
decided by if statement. Consider the following example.
Example
1. i = 18
2. if (1 < 12):
3. print("I am less than 18")
Output:
I am less than 18
13. else - The else statement is used with the if statement. When if statement returns false, then
else block is executed. Consider the following example.
Example:
1. n = 11
2. if(n%2 == 0):
3. print("Even")
4. else:
5. print("odd")
Output:
Odd
14. elif - This Keyword is used to check the multiple conditions. It is short for else-if. If the
previous condition is false, then check until the true condition is found. Condition the following
example.
Example:
1. marks = int(input("Enter the marks:"))
2. if(marks>=90):
3. print("Excellent")
4. elif(marks<90 and marks>=75):
5. print("Very Good")
6. elif(marks<75 and marks>=60):
7. print("Good")
8. else:
9. print("Average")
Output:
15. del - It is used to delete the reference of the object. Consider the following example.
Example:
1. a=10
2. b=12
3. del a
4. print(b)
5. # a is no longer exist
6. print(a)
Output:
12
NameError: name 'a' is not defined
16. try, except - The try-except is used to handle the exceptions. The exceptions are run-time
errors. Consider the following example.
Example:
1. a = 0
2. try:
3. b = 1/a
4. except Exception as e:
5. print(e)
Output:
division by zero
17. raise - The raise keyword is used to through the exception forcefully. Consider the following
example.
Example
1. a = 5
2. if (a>2):
3. raise Exception('a should not exceed 2 ')
Output:
18. finally - The finally keyword is used to create a block of code that will always be executed
no matter the else block raises an error or not. Consider the following example.
Example:
1. a=0
2. b=5
3. try:
4. c = b/a
5. print(c)
6. except Exception as e:
7. print(e)
8. finally:
9. print('Finally always executed')
Output:
division by zero
Finally always executed
19. for, while - Both keywords are used for iteration. The for keyword is used to iterate over the
sequences (list, tuple, dictionary, string). A while loop is executed until the condition returns
false. Consider the following example.
1. list = [1,2,3,4,5]
2. for i in list:
3. print(i)
Output:
1
2
3
4
5
Output:
0
1
2
3
4
20. import - The import keyword is used to import modules in the current Python script. The
module contains a runnable Python code.
Example:
1. import math
2. print(math.sqrt(25))
Output:
21. from - This keyword is used to import the specific function or attributes in the current
Python script.
Example:
1. from math import sqrt
2. print(sqrt(25))
Output:
22. as - It is used to create a name alias. It provides the user-define name while importing a
module.
Example:
1. import calendar as cal
2. print(cal.month_name[5])
Output:
May
23. pass - The pass keyword is used to execute nothing or create a placeholder for future code. If
we declare an empty class or function, it will through an error, so we use the pass keyword to
declare an empty class or function.
Example:
1. class my_class:
2. pass
3.
4. def my_func():
5. pass
24. return - The return keyword is used to return the result value or none to called function.
Example:
1. def sum(a,b):
2. c = a+b
3. return c
4.
5. print("The sum is:",sum(25,15))
Output:
25. is - This keyword is used to check if the two-variable refers to the same object. It returns the
true if they refer to the same object otherwise false. Consider the following example.
Example
1. x = 5
2. y = 5
3.
4. a = []
5. b = []
6. print(x is y)
7. print(a is b)
Output:
True
False
Note: A mutable data-types do not refer to the same object.
26. global - The global keyword is used to create a global variable inside the function. Any
function can access the global. Consider the following example.
Example
1. def my_func():
2. global a
3. a = 10
4. b = 20
5. c = a+b
6. print(c)
7.
8. my_func()
9.
10. def func():
11. print(a)
12.
13. func()
27. nonlocal - The nonlocal is similar to the global and used to work with a variable inside the
nested function(function inside a function). Consider the following example.
Example
1. def outside_function():
2. a = 20
3. def inside_function():
4. nonlocal a
5. a = 30
6. print("Inner function: ",a)
7. inside_function()
8. print("Outer function: ",a)
9. outside_function()
Output:
Inner function: 50
Outer function: 50
28. lambda - The lambda keyword is used to create the anonymous function in Python. It is an
inline function without a name. Consider the following example.
Example
1. a = lambda x: x**2
2. for i in range(1,6):
3. print(a(i))
Output:
1
4
9
16
25
29. yield - The yield keyword is used with the Python generator. It stops the function's execution
and returns value to the caller. Consider the following example.
Example
1. def fun_Generator():
2. yield 1
3. yield 2
4. yield 3
5.
6.
7. # Driver code to check above generator function
8. for value in fun_Generator():
9. print(value)
Output:
1
2
3
30. with - The with keyword is used in the exception handling. It makes code cleaner and more
readable. The advantage of using with, we don't need to call close(). Consider the following
example.
Example
1. with open('file_path', 'w') as file:
2. file.write('hello world !')
31. None - The None keyword is used to define the null value. It is remembered that None does
not indicate 0, false, or any empty data-types. It is an object of its data type, which is Consider
the following example.
Example:
1. def return_none():
2. a = 10
3. b = 20
4. c = a + b
5.
6. x = return_none()
7. print(x)
Output:
None
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:
1. "Aman" , '12345'
Types of Strings:
a) Single-line String- Strings that are terminated within a single-line are known as Single line
Strings.
Example:
1. text1='hello'
b) Multi-line String - A piece of text that is written in multiple lines is known as multiple lines
string.
Example:
1. text1='hello\
2. user'
3. print(text1)
'hellouser'
Example:
1. str2='''''welcome
2. to
3. SSSIT'''
4. print str2
Output:
welcome
to
SSSIT
Numeric Literals are immutable. Numeric literals can belong to following four different
numerical types.
Int(signed float(floating
Long(long integers) Complex(complex)
integers) point)
Numbers( can be Integers of unlimited
Real numbers with In the form of a+bj where a
both positive and size followed by
both integer and forms the real part and b forms
negative) with no lowercase or
fractional part eg: the imaginary part of the
fractional part.eg: uppercase L eg:
-26.2 complex number. eg: 3.14j
100 87032845L
1. x = 0b10100 #Binary Literals
2. y = 100 #Decimal Literal
3. z = 0o215 #Octal Literal
4. u = 0x12d #Hexadecimal Literal
5.
6. #Float Literal
7. float_1 = 100.5
8. float_2 = 1.5e2
9.
10. #Complex Literal
11. a = 5+3.14j
12.
13. print(x, y, z, u)
14. print(float_1, float_2)
15. print(a, a.imag, a.real)
Output:
A Boolean literal can have any of the two values: True or False.
1. x = (1 == True)
2. y = (2 == False)
3. z = (3 == True)
4. a = True + 10
5. b = False + 10
6.
7. print("x is", x)
8. print("y is", y)
9. print("z is", z)
10. print("a:", a)
11. 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.
1. val1=10
2. val2=None
3. print(val1)
4. 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.
List:
List contains items of different data types. Lists are mutable i.e., modifiable.
The values stored in List are separated by comma(,) and enclosed within square
brackets([]). We can store different types of data in a List.
1. list=['John',678,20.4,'Peter']
2. list1=[456,'Andrew']
3. print(list)
4. print(list + list1)
Output:
Dictionary:
Example
1. dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}
2. print(dict)
Output:
Tuple:
Example
1. tup = (10,20,"Dev",[2,3,4])
2. print(tup)
Output:
Set:
1. set = {'apple','grapes','guava','papaya'}
2. print(set)
Output: