Python Tutorial1
Python Tutorial1
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.
1. Python 2 uses print as a statement and used as print "something" to print some
string on the console. On the other hand, Python 3 uses print as a function and
used as print("something") to print something on the console.
2. Python 2 uses the function raw_input() to accept the user's input. It returns the
string representing the value, which is typed by the user. To convert it into the
integer, we need to use the int() function in Python. On the other hand, Python 3
uses input() function which automatically interpreted the type of input entered
by the user. However, we can cast this value to any type by using primitive
functions (int(), str(), etc.).
3. In Python 2, the implicit string type is ASCII, whereas, in Python 3, the implicit
string type is Unicode.
4. Python 3 doesn't contain the xrange() function of Python 2. The xrange() is the
variant of range() function which returns a xrange object that works similar to
Java iterator. The range() returns a list for example the function range(0,3)
contains 0, 1, 2.
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.
o Expressive Language
o Interpreted Language
o Object-Oriented Language
o Extensible
o Integrated
o Embeddable
o Data Science
o Date Mining
o Desktop Applications
o Console-based Applications
o Mobile Applications
o Software Development
o Artificial Intelligence
o Web Applications
o Enterprise Applications
o 3D CAD Applications
o Machine Learning
o Speech Recognitions
1. def func():
2. statement 1
3. statement 2
4. …………………
5. …………………
6. statement N
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. 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.
print("Welcome to TNU.")
a = 10
# Two objects are passed in print() function
print("a =", a)
b=a
# Three objects are passed in print function
print('a =', a, '= b')
Output:
Welcome to TNU
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.
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.
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.
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.
o In February 1991, Guido Van Rossum published the code (labeled version
0.9.0) to alt.sources.
o In 1994, Python 1.0 was released with new features like lambda, map, filter, and
reduce.
o Python 2.0 added new features such as list comprehensions, garbage collection
systems.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was
designed to rectify the fundamental flaw of the language.
o ABC language.
o Modula-3
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 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.
o Tkinter or Tk
o wxWidgetM
o 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.
o Buildbot and Apache Gumps are used for automated continuous compilation
and testing.
o SciPy
o Scikit-learn
o NumPy
o Pandas
o 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.
o Gstreamer
o Pyglet
o 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.
o Fandango (Popular )
o CAMVOX
o HeeksCNC
o AnyCAD
o 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.
o Pillow
o 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.
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.
After writing the print statement, press the Enter key.
Here, we get the message "Hello World !" printed on the console.
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.
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.
o All the characters except the first character may be an alphabet of lower-case(a-
z), upper-case (A-Z), underscore, or digit (0-9).
o Identifier name must not contain any white-space, or special character (!, @, #,
%, ^, &, *).
o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive; for example, my name, and MyName is not
the same.
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'>
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.
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, na5
6me)
Output:
A B C D E D E F G F I
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
Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a = 4
A = "Sally"
#A will not overwrite a
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
1. a = 5
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'>
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.
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.
In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
Example - 1
Output:
Example - 2
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.
Output:
A tuple is a read-only data structure as we can't modify the size and value of the items
of a tuple.
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative
array or a hash table where each key stores a specific value. Key can hold any primitive
data type, whereas value is an arbitrary Python object.
The items in the dictionary are separated with the comma (,) and enclosed in the curly
braces {}.
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.
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.
Output:
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.
A B A and B
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
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:
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
1. a = 0
2. while(a<5):
3. print(a)
4. a = a+1
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:
Output:
22. as - It is used to create a name alias. It provides the user-define name while
importing a module.
Example:
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()
Output:
30
10
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 Operators
The operator can be defined as a symbol which is responsible for a particular operation
between two operands. Operators are the pillars of a program on which the logic is built
in a specific programming language. Python provides a variety of operators, which are
described as follows.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations between two operands.
It includes + (addition), - (subtraction), *(multiplication), /(divide), %(reminder),
//(floor division), and exponent (**) operators.
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b =
30
- (Subtraction) It is used to subtract the second operand from the first operand. If the
first operand is less than the second operand, the value results negative.
For example, if a = 20, b = 10 => a - b = 10
/ (divide) It returns the quotient after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a = 20,
(Multiplication) b = 10 => a * b = 200
% (reminder) It returns the reminder after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a%b = 0
// (Floor It gives the floor value of the quotient produced by dividing the two
division) operands.
Comparison operator
Comparison operators are used to comparing the value of the two operands and returns
Boolean true or false accordingly. The comparison operators are described in the
following table.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= If the first operand is less than or equal to the second operand, then the
condition becomes true.
>= If the first operand is greater than or equal to the second operand, then the
condition becomes true.
> If the first operand is greater than the second operand, then the condition
becomes true.
< If the first operand is less than the second operand, then the condition becomes
true.
Assignment Operators
The assignment operators are used to assign the value of the right expression to the
left operand. The assignment operators are described in the following table.
Operator Description
+= It increases the value of the left operand by the value of the right operand and
assigns the modified value back to left operand. For example, if a = 10, b = 20
=> a+ = b will be equal to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and
assigns the modified value back to left operand. For example, if a = 20, b = 10
=> a- = b will be equal to a = a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and
assigns the modified value back to then the left operand. For example, if a = 10,
b = 20 => a* = b will be equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and
assigns the reminder back to the left operand. For example, if a = 20, b = 10 =>
a % = b will be equal to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign
4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign
4//3 = 1 to a.
Bitwise Operators
The bitwise operators perform bit by bit operation on the values of the two operands.
Consider the following example.
For example,
1. if a = 7
2. b=6
3. then, binary (a) = 0111
4. binary (b) = 0011
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000
Operator Description
& (binary If both the bits at the same place in two operands are 1, then 1 is copied
and) to the result. Otherwise, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting
bit will be 1.
^ (binary The resulting bit will be 1 if both the bits are different; otherwise, the
xor) resulting bit will be 0.
~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is 0, the
resulting bit will be 1 and vice versa.
<< (left The left operand value is moved left by the number of bits present in the
shift) right operand.
>> (right The left operand is moved right by the number of bits present in the right
shift) operand.
Logical Operators
The logical operators are used primarily in the expression evaluation to make a
decision. Python supports the following logical operators.
Operator Description
and If both the expression are true, then the condition will be true. If a and b are
the two expressions, a → true, b → true => a and b → true.
or If one of the expressions is true, then the condition will be true. If a and b are
the two expressions, a → true, b → false => a or b → true.
not If an expression a is true, then not (a) will be false and vice versa.
Membership Operators
Python membership operators are used to check the membership of value inside a
Python data structure. If the value is present in the data structure, then the resulting
value is true otherwise it returns false.
Operator Description
not in It is evaluated to be true if the first operand is not found in the second operand
(list, tuple, or dictionary).
Identity Operators
The identity operators are used to decide whether an element certain class or type.
Operator Description
is not It is evaluated to be true if the reference present at both sides do not point
to the same object.
Operator Precedence
The precedence of the operators is essential to find out since it enables us to know
which operator should be evaluated first. The precedence table of the operators in
Python is given below.
Operator Description
** The exponent operator is given priority over all the others used in
the expression.
<= < > >= Comparison operators (less than, less than equal to, greater than,
greater then equal to).
In the other programming language such as C++, It provides the // for single-lined
comment and /*.... */ for multiple-lined comment, but Python provides the single-lined
Python comment. To apply the comment in the code we use the hash(#) at the
beginning of the statement or code.
Here we have written comment over the print statement using the hash(#). It will not
affect our print statement.
Example:
The above code is very readable even the absolute beginners can under that what is
happening in each line of the code. This is the advantage of using comments in code.
We can also use the triple quotes ('''''') for multiline comment. The triple quotes are
also used to string formatting. Consider the following example.
Example:
1. def intro():
2. """
3. This function prints Hello Joseph
4. """
5. print("Hi Joseph")
6. intro()
Output:
Hello Joseph
Generally, four whitespaces are used as the indentation. The amount of indentation
depends on user, but it must be consistent throughout that block.
1. def intro():
2. """
3. This function prints Hello Joseph
4. """
5. print("Hello Joseph")
6. intro.__doc__
Output:
Output:
'\n This function prints Hello Joseph\n '
Note: The docstring must be the first thing in the function; otherwise, Python
interpreter cannot get the docstring.
Python indentation
Python indentation uses to define the block of the code. The other programming
languages such as C, C++, and Java use curly braces {}, whereas Python uses an
indentation. Whitespaces are used as indentation in Python.
Indentation uses at the beginning of the code and ends with the unintended line. That
same line indentation defines the block of the code (body of a function, loop, etc.)
Generally, four whitespaces are used as the indentation. The amount of indentation
depends on user, but it must be consistent throughout that block.
1. for i in range(5):
2. print(i)
3. if(i == 3):
4. break
To indicate a block of code we indented each line of the block by the same whitespaces.
Output:
The above code, if and else are two separate code blocks. Both code blocks are
indented four spaces. The print("Task Complete") statement is not indented four
whitespaces and it is out of the if-else block.
If the indentation is not used properly, then that will result in IndentationError.