Python Basic
Python Basic
PYTHON BASIC
CHAPTER -I
PYTHON - OVERVIEW
Python is a high-level, multi-paradigm programming language. As Python is an
interpreter-based language, it is easier to learn compared to some of the other
mainstream languages. Python is a dynamically typed language with very
intuitive data types.
Python is an open-source and cross-platform programming language. It is
available for use under Python Software Foundation License (compatible to
GNU General Public License) on all the major operating system platforms
Linux, Windows and Mac OS.
The design philosophy of Python emphasizes on simplicity, readability and
unambiguity. Python is known for its batteries included approach as Python
software is distributed with a comprehensive standard library of functions and
modules.
Python's design philosophy is documented in the Zen of Python. It consists of
nineteen aphorisms such as −
Beautiful is better than ugly
Explicit is better than implicit
Simple is better than complex
Complex is better than complicated
To obtain the complete Zen of Python document, type import this in the Python
shell −
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
1
Python Basic
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Python supports imperative, structured as well as object-oriented programming
methodology. It provides features of functional programming as well.
PYTHON - HISTORY
Guido Van Rossum, a Dutch programmer, created Python programming
language. In the late 80's, he had been working on the development of ABC
language in a computer science research institute named Centrum Wiskunde
& Informatica (CWI) in the Netherlands. In 1991, Van Rossum conceived and
published Python as a successor of ABC language.
For many uninitiated people, the word Python is related to a species of snake.
Rossum though attributes the choice of the name Python to a popular comedy
series "Monty Python's Flying Circus" on BBC.
Being the principal architect of Python, the developer community conferred
upon him the title of "Benevolent Dictator for Life (BDFL). However, in
2018, Rossum relinquished the title. Thereafter, the development and
distribution of the reference implementation of Python is handled by a nonprofit
organization Python Software Foundation.
Important stages in the history of Python −
Python 0.9.0
Python's first published version is 0.9. It was released in February 1991. It
consisted of support for core object-oriented programming principles.
Python 1.0
In January 1994, version 1.0 was released, armed with functional programming
tools, features like support for complex numbers etc.
Python 2.0
Next major version − Python 2.0 was launched in October 2000. Many new
features such as list comprehension, garbage collection and Unicode support
were included with it.
Python 3.0
2
Python Basic
Python - Features
In this chapter, let's highlight some of the important features of Python that
make it widely popular.
Python is Easy to Learn
This is one of the most important reasons for the popularity of Python. Python
has a limited set of keywords. Its features such as simple syntax, usage of
3
Python Basic
indentation to avoid clutter of curly brackets and dynamic typing that doesn't
necessitate prior declaration of variable help a beginner to learn Python quickly
and easily.
Python is Interpreter Based
Instructions in any programming languages must be translated into machine
code for the processor to execute them. Programming languages are either
compiler based or interpreter based.
In case of a compiler, a machine language version of the entire source program
is generated. The conversion fails even if there is a single erroneous statement.
Hence, the development process is tedious for the beginners. The C family
languages (including C, C++, Java, C Sharp etc) are compiler based.
Python is an interpreter based language. The interpreter takes one instruction
from the source code at a time, translates it into machine code and executes it.
Instructions before the first occurrence of error are executed. With this feature,
it is easier to debug the program and thus proves useful for the beginner level
programmer to gain confidence gradually. Python therefore is a beginner-
friendly language.
Python is Interactive
Standard Python distribution comes with an interactive shell that works on the
principle of REPL (Read − Evaluate − Print − Loop). The shell presents a
Python prompt >>>. You can type any valid Python expression and press Enter.
Python interpreter immediately returns the response and the prompt comes back
to read the next expression.
>>> 2*3+1
7
>>> print ("Hello World")
Hello World
The interactive mode is especially useful to get familiar with a library and test
out its functionality. You can try out small code snippets in interactive mode
before writing a program.
PYTHON IS MULTIPARADIGM
Python is a completely object-oriented language. Everything in a Python
program is an object. However, Python conveniently encapsulates its object
orientation to be used as an imperative or procedural language − such as C.
Python also provides certain functionality that resembles functional
programming. Moreover, certain third-party tools have been developed to
4
Python Basic
5
Python Basic
Python is Extensible
The term extensibility implies the ability to add new features or modify existing
features. As stated earlier, CPython (which is Python's reference
implementation) is written in C. Hence one can easily write modules/libraries in
C and incorporate them in the standard library. There are other implementations
of Python such as Jython (written in Java) and IPython (written in C#). Hence, it
is possible to write and merge new functionality in these implementations with
Java and C# respectively.
6
Python Basic
Compiled vs Interpreted
Like C, C++ is also a compiler-based language. A compiler translates the entire
code in a machine language code specific to the operating system in use and
processor architecture.
Python is interpreter-based language. The interpreter executes the source code
line by line.
Cross platform
When a C++ source code such as hello.cpp is compiled on Linux, it can be only
run on any other computer with Linux operating system. If required to run on
other OS, it needs to be compiled.
Python interpreter doesn't produce compiled code. Source code is converted to
byte code every time it is run on any operating system without any changes or
additional steps.
Portability
Python code is easily portable from one OS to other. C++ code is not portable as
it must be recompiled if the OS changes.
Speed of Development
C++ program is compiled to the machine code. Hence, its execution is faster
than interpreter based language.
Python interpreter doesn't generate the machine code. Conversion of
intermediate byte code to machine language is done on each execution of
program.
If a program is to be used frequently, C++ is more efficient than Python.
Easy to Learn
Compared to C++, Python has a simpler syntax. Its code is more readable.
Writing C++ code seems daunting in the beginning because of complicated
syntax rule such as use of curly braces and semicolon for sentence termination.
Python doesn't use curly brackets for marking a block of statements. Instead, it
uses indents. Statements of similar indent level mark a block. This makes a
Python program more readable.
Static vs Dynamic Typing
C++ is a statically typed language. The type of variables for storing data need to
be declared in the beginning. Undeclared variables can't be used. Once a
7
Python Basic
variable is declared to be of a certain type, value of only that type can be stored
in it.
Python is a dynamically typed language. It doesn't require a variable to be
declared before assigning it a value. Since, a variable may store any type of
data, it is called dynamically typed.
OOP Concepts
Both C++ and Python implement object oriented programming concepts. C++ is
closer to the theory of OOP than Python. C++ supports the concept of data
encapsulation as the visibility of the variables can be defined as public, private
and protected.
Python doesn't have the provision of defining the visibility. Unlike C++, Python
doesn't support method overloading. Because it is dynamically typed, all the
methods are polymorphic in nature by default.
C++ is in fact an extension of C. One can say that additional keywords are
added in C so that it supports OOP. Hence, we can write a C type procedure
oriented program in C++.
Python is completely object oriented language. Python's data model is such that,
even if you can adapt a procedure oriented approach, Python internally uses
object-oriented methodology.
Garbage Collection
C++ uses the concept of pointers. Unused memory in a C++ program is not
cleared automatically. In C++, the process of garbage collection is manual.
Hence, a C++ program is likely to face memory related exceptional behavior.
Python has a mechanism of automatic garbage collection. Hence, Python
program is more robust and less prone to memory related issues.
Application Areas
Because C++ program compiles directly to machine code, it is more suitable for
systems programming, writing device drivers, embedded systems and operating
system utilities.
Python program is suitable for application programming. Its main area of
application today is data science, machine learning, API development etc.
The following table summarizes the comparison between C++ and Python
8
Python Basic
C++ Python
Criteria
Execution Compiler based Interpreter based
Typing Static typing Dynamic typing
Portability Not portable Highly portable
Garbage
Manual Automatic
collection
Syntax Tedious Simple
Performance Faster execution Slower execution
Embedded systems, device Machine learning, web
Application areas
drivers applications
9
Python Basic
For Windows OS, open the command prompt terminal (CMD) and run the
program as shown below −
C:\Python311>python hello.py
Hello World
The terminal shows the Hello World message.
While working on Ubuntu Linux, you have to follow the same steps, save the
code and run from Linux terminal. We use vi editor for saving the program.
10
Python Basic
Thus, we can write and run Hello World program in Python using the interpreter
mode and script mode.
11
Python Basic
12
Python Basic
Many software products like Maya embed Python API for writing automation
scripts (something similar to Excel micros).
Try Python Online
If you are new to Python, it is a good idea to get yourself familiar with the
language syntax and features by trying out one of the many online resources,
before you proceed to install Python software on your computer.
You can launch Python interactive shell from the home page of Python's official
website
In front of the Python prompt (>>>), any valid Python expression can be
entered and evaluated.
13
Python Basic
Python - Interpreter
Python is an interpreter-based language. In a Linux system, Python's executable
is installed in /usr/bin/ directory. For Windows, the executable (python.exe) is
found in the installation folder (for example C:\python311). In this chapter, you
will how Python interpreter works, its interactive and scripted mode.
Python code is executed by one statement at a time method. Python interpreter
has two components. The translator checks the statement for syntax. If found
correct, it generates an intermediate byte code. There is a Python virtual
machine which then converts the byte code in native binary and executes it. The
following diagram illustrates the mechanism:
Interactive Mode
When launched from a command line terminal without any additional options, a
Python prompt >>> appears and the Python interpreter works on the principle of
REPL (Read, Evaluate, Print, Loop). Each command entered in front of the
14
Python Basic
Scripting Mode
Instead of entering and obtaining the result of one instruction at a time − as in
the interactive environment, it is possible to save a set of instructions in a text
file, make sure that it has .py extension, and use the name as the command line
parameter for Python command.
Save the following lines as prog1.py, with the use of any text editor such as
vim on Linux or Notepad on Windows.
print ("My first program")
price = 100
qty = 5
ttl = price*qty
print ("Total = ", ttl)
Launch Python with this name as command line argument.
C:\Users\Acer>python prog1.py
My first program
Total = 500
Note that even though Python executes the entire script, it is still executed in
one-by-one fashion.
In case of any compiler-based language such as Java, the source code is not
converted in byte code unless the entire code is error-free. In Python, on the
15
Python Basic
16
Python Basic
IPython
IPython (stands for Interactive Python) is an enhanced and powerful
interactive environment for Python with many functionalities compared to the
standard Python shell. IPython was originally developed by Fernando Perez in
2001.
IPython has the following important features −
IPython's object introspection ability to check properties of an object
during runtime.
Its syntax highlighting proves to be useful in identifying the language
elements such as keywords, variables etc.
The history of interactions is internally stored and can be reproduced.
Tab completion of keywords, variables and function names is one of the
most important features.
IPython's Magic command system is useful for controlling Python
environment and performing OS tasks.
It is the main kernel for Jupyter notebook and other front-end tools of
Project Jupyter.
Install IPython with PIP installer utility.
pip3 install ipython
Launch IPython from command-line
C:\Users\Acer>ipython
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934
64 bit (AMD64)] on win32
Type 'copyright', 'credits' or 'license' for more information
IPython 8.4.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]:
Instead of the regular >>> prompt as in standard interpreter, you will notice two
major IPython prompts as explained below −
In[1] appears before any input expression.
Out[1]appears before the Output appears.
In [1]: price = 100
In [2]: quantity = 5
In [3]: ttl = price*quantity
In [4]: ttl
Out[4]: 500
In [5]:
17
Python Basic
Directory of F:\Python311
18
Python Basic
19
Python Basic
20
Python Basic
Although you can straight away proceed by clicking the Install Now button, it is
advised to choose the installation folder with a relatively shorter path, and tick
the second check box to update the PATH variable.
Accept defaults for rest of the steps in this installation wizard to complete the
installation.
Open the Window Command Prompt terminal and run Python to check the
success of installation.
21
Python Basic
C:\Users\Acer>python
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934
64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
Python's standard library has an executable module called IDLE − short for
Integrated Development and Learning Environment. Find it from Window
start menu and launch.
The frequently required utilities such as PIP and IDLE are also installed by this
installation wizard.
Alternately, you can opt for the installation from command line. You need to
install Homebrew, Mac's package manager, if it is not already available. You
can follow the instructions for installation at https://docs.brew.sh/Installation.
After that, open the terminal and enter the following commands −
brew update && brew upgrade
brew install python3
23
Python Basic
If you are an experienced developer, with good knowledge of C++ and Git tool,
you can follow the instructions in this section to build Python executable along
with the modules in the standard library.
You must have the C compiler for the OS that you are on. In Ubuntu and
MacOS, gcc compiler is available. For Windows, you should install Visual
Studio 2017 or later.
Windows installed. Clone the Python source code repository by the same
command as above.
Open the windows command prompt in the folder where the source code is
placed. Run the following batch file
PCbuild\get_externals.bat
This downloads the source code dependencies (OpenSSL, Tk etc.)
Open Visual Studio and PCbuild/sbuild.sln solution, and build (press F10) the
debug folder shows python_d.exe which is the debug version of Python
executable.
To build from command prompt, use the following command −
24
Python Basic
PCbuild\build.bat -e -d -p x64
Thus, in this chapter, you learned how to install Python from the pre-built
binaries as well as from the source code.
25
Python Basic
Edit the Path variable, and add a new entry. Enter the name of the installation
folder in which Python has been installed, and press OK.
26
Python Basic
To add the Python directory to the path for a particular session in Linux −
27
Python Basic
28
Python Basic
Python environment variables may be set temporarily for the current session or
may be persistently added in the System Properties as in case of path variable.
PYTHONPATH
As mentioned above, if you want the interpreter should search for a module in
other folders in addition to the current, one or more such folder locations are
stored as PYTHONPATH variable.
First, save hello.py script in a folder different from Python's installation folder,
let us say c:\modulepath\hello.py
To make the module available to the interpreter globally, set PYTHONPATH
C:\Users\Acer>set PYTHONPATH= c:\modulepath
C:\Users\Acer>echo %PYTHONPATH%
c:\modulepath
Now you can import the module even from any directory other than c:\
modulepath directory.
>>> import hello
Hello World
>>>
29
Python Basic
CHAPTER -2
PYTHON HOME
Set this variable to change the location of the standard Python libraries. By
default, the libraries are searched in /usr/local/pythonversion in case of Linux
and instalfolder\lib in Windows. For example, c:\python311\lib.
PYTHON STARTUP
Usually, this variable is set to a Python script, which you intend to get
automatically executed every time Python interpreter starts.
Let us create a simple script as follows and save it as startup.py in the Python
installation folder −
print ("Example of Start up file")
print ("Hello World")
Now set the PYTHONSTARTUP variable and assign name of this file to it.
After that start the Python interpreter. It shows the output of this script before
you get the prompt.
F:\311_2>set PYTHONSTARTUP=startup.py
F:\311_2>echo %PYTHONSTARTUP%
startup.py
F:\311_2>python
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934
64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Example of Start up file
Hello World
>>>
PYTHONCASEOK
This environment is available for use only on Windows and MacOSX, not on
Linux. It causes Python to ignore the cases in import statement.
PYTHONVERBOSE
If this variable is set to a non-empty string it is equivalent to specifying python -
v command. It results in printing a message, showing the place (filename or
built-in module) each time a module is initialized. If set to an integer − say 2, it
is equivalent to specifying -v two times. (python --v).
30
Python Basic
PYTHONDONTWRITEBYTECODE
Normally, the imported modules are compiled to .pyc file. If this variable is set
to a not null string,the .pyc files on the import of source modules are not
created.
PYTHONWARNINGS
Python's warning messages are redirected to the standard error stream,
sys.stderr. This environment variable is equivalent to the python -W option.
The following are allowed values of this variable −
# Warn once per call location PYTHONWARNINGS=default
PYTHONWARNINGS=error # Convert to exceptions
# Warn every time PYTHONWARNINGS=always
# Warn once per calling module PYTHONWARNINGS=module
PYTHONWARNINGS=once # Warn once per Python process
# Never warn PYTHONWARNINGS=ignore
31
Python Basic
33
Python Basic
meaning, they must be used only for its predefined purpose and as per the
predefined rules of syntax. Programming logic is encoded with these keywords.
As of Python 3.11 version, there are 35 (Thirty Five) keywords in Python. To
obtain the list of Python keywords, enter the following help command in Python
shell.
>>> help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more
help.
1. False 10. class 19. from 28. or
2. None 11. continue 20. global 29. pass
3. True 12. def 21. if 30. raise
4. and 13. del 22. import 31. return
5. as 14. elif 23. in 32. try
6. assert 15. else 24. is 33. while
7. async 16. except 25. lambda 34. with
8. await 17. finally 26. nonlocal 35. yield
9. break 18. for 27. not
All the keywords are alphabetic and all (except False, None and True) are in
lowercase. The list of keywords is also given by kwlist property defined in
keyword module
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']
How to verify if any word is a keyword or not? Most Python IDEs provide
coloured syntax highlighting feature, where keywords are represented in a
specific colour.
Shown below is a Python code in VS Code. Keywords (if and else), identifiers
and constants appear in distinct colour scheme.
34
Python Basic
The keyword module also has a iskeyword() function. It returns True for a valid
keyword, False otherwise.
>>> import keyword
>>> keyword.iskeyword("else")
True
>>> keyword.iskeyword("Hello")
False
Python keywords can be broadly classified in following categories −
Value Keywords True, False, None
Operator Keywords and, or, not, in, is
Conditional Flow Keywords if, elif, else
Keywords for loop control for, while, break, continue
Structure Keywords def, class, with, pass, lambda
Keywords for returning return, yield
Import Keywords import, from, as
Keywords about ExceptionHandling try, except, raise, finally, assert
Keywords for Asynchronous Programming async, await
Variable Scope Keywords del, global, nonlocal
We shall learn about the usage of each of these keywords as we go along in this
tutorial.
Python Identifiers
35
Python Basic
36
Python Basic
At this juncture, you may not understand how the code works. But don't worry.
Just see how indent level increases after colon symbol.
PYTHON STATEMENTS
A statement in Python is any instruction that the Python interpreter can execute.
A statement comprises of one or more keywords, operators, identifiers, a :
symbol to mark beginning of block, or backslash \ as continuation character.
The statement may be a simple assignment statement such as amount = 1000 or
it may be a compound statement with multiple statements grouped together in
uniformly indented block, as in conditional or looping constructs.
37
Python Basic
You can enter a statement in front of the Python prompt of the interactive shell,
or in the editor window. Usually, text terminated by Enter key (called newline
character) is recognized as a statement by Python interpreter. Hence, each line
in the editor is a statement, unless it starts with the comment character (#).
print ("My first program")
price = 100
qty = 5
ttl = price*qty
print ("Total = ", ttl)
Each line in the above code is a statement. Occasionally, a Python statement
may spill over multiple lines. To do so, use backslash (\) as continuation
character. A long string can be conveniently broken in multiple lines as shown
below −
name = "Ravi"
string = "Hello {} \
Welcome to Python Tutorial \
from TutorialsPoint".format(name)
print (string)
The string (with an embedded string variable name) spreads over multiple lines
for better readability. The output will be −
Hello Ravi Welcome to Python Tutorial from TutorialsPoint
The continuation character also helps in writing a long arithmetic expression in
a more readable manner.
For example, the equation (a+b)×(c−d)(a−b)×(c+d)
is coded in Python as follows −
a=10
b=5
c=5
d=10
expr = (a+b)*(c-d)/ \
(a-b)*(c+d)
print (expr)
The use of back-slash symbol (\) is not necessary if items in a list, tuple or
dictionary object spill over multiple lines.
Subjects = ["English", "French", "Sanskrit",
"Physics", "Maths",
"Computer Sci", "History"]
38
Python Basic
Python also allows use of semicolon to put more than one statements in a single
line in the editor. Look at the following examples −
a=10; b=5; c=5; d=10
if a>10: b=20; c=50
PYTHON - VARIABLES
In this chapter, you will learn what are variables in Python and how to use them.
Data items belonging to different data types are stored in computer's memory.
Computer's memory locations are having a number or address, internally
represented in binary form. Data is also stored in binary form as the computer
works on the principle of binary representation. In the following diagram, a
string May and a number 18 is shown as stored in memory locations.
If you know the assembly language, you will covert these data items and the
memory address, and give a machine language instruction. However, it is not
easy for everybody. Language translator such as Python interpreter performs
this type of conversion. It stores the object in a randomly chosen memory
39
Python Basic
location. Python's built-in id() function returns the address where the object is
stored.
>>> "May"
>>> id("May")
2167264641264
>>> 18
18
>>> id(18)
140714055169352
Once the data is stored in the memory, it should be accessed repeatedly for
performing a certain process. Obviously, fetching the data from its ID is
cumbersome. High level languages like Python make it possible to give a
suitable alias or a label to refer to the memory location.
In the above example, let us label the location of May as month, and location in
which 18 is stored as age. Python uses the assignment operator (=) to bind an
object with the label.
>>> month="May"
>>> age=18
The data object (May) and its name (month) have the same id(). The id() of 18
and age are also same.
>>> id(month)
2167264641264
>>> id(age)
140714055169352
The label is an identifier. It is usually called as a variable. A Python variable is a
symbolic name that is a reference or pointer to an object.
Naming Convention
Name of the variable is user specified, and is formed by following the rules of
forming an identifier.
Name of Python variable should start with either an alphabet (lower or
upper case) or underscore (_). More than one alpha-numeric characters or
underscores may follow.
Use of any keyword as Python variable is not allowed, as keywords have
a predefined meaning.
Name of a variable in Python is case sensitive. As a result, age and Age
cannot be used interchangeably.
40
Python Basic
You should choose the name of variable that is mnemonic, such that it
indicates the purpose. It should not be very short, but not vary lengthy
either.
If the name of variable contains multiple words, we should use these naming
patterns −
Camel case − First letter is a lowercase, but first letter of each
subsequent word is in uppercase. For example: kmPerHour, pricePerLitre
Pascal case − First letter of each word is in uppercase. For example:
KmPerHour, PricePerLitre
Snake case − Use single underscore (_) character to separate words. For
example: km_per_hour, price_per_litre
Once you use a variable to identify a data object, it can be used repeatedly
without its id() value. Here, we have a variables height and width of a rectangle.
We can compute the area and perimeter with these variables.
>>> width=10
>>> height=20
>>> area=width*height
>>> area
200
>>> perimeter=2*(width+height)
>>> perimeter
60
Use of variables is especially advantageous when writing scripts or programs.
Following script also uses the above variables.
#! /usr/bin/python3.11
width = 10
height = 20
area = width*height
perimeter = 2*(width+height)
print ("Area = ", area)
print ("Perimeter = ", perimeter)
Save the above script with .py extension and execute from command-line. The
result would be −
Area = 200
Perimeter = 60
Assignment Statement
41
Python Basic
In languages such as C/C++ and Java, one needs to declare the variable and its
type before assigning it any value. Such prior declaration of variable is not
required in Python.
Python uses = symbol as the assignment operator. Name of the variable
identifier appears on the left of = symbol. The expression on its right id
evaluated and the value is assigned to the variable. Following are the examples
of assignment statements
>>> counter = 10
>>> counter = 10 # integer assignment
>>> price = 25.50 # float assignment
>>> city = "Hyderabad" # String assignment
>>> subjects = ["Physics", "Maths", "English"] # List assignment
>>> mark_list = {"Rohit":50, "Kiran":60, "Lata":70} # dictionary
assignment
Python's built-in print() function displays the value of one or more variables.
>>> print (counter, price, city)
10 25.5 Hyderabad
>>> print (subjects)
['Physics', 'Maths', 'English']
>>> print (mark_list)
{'Rohit': 50, 'Kiran': 60, 'Lata': 70}
Value of any expression on the right of = symbol is assigned to the variable on
left.
>>> x = 5
>>> y = 10
>>> z = x+y
However, the expression on the left and variable on the right of = operator is not
allowed.
>>> x = 5
>>> y = 10
>>> x+y=z
File "<stdin>", line 1
x+y=z
^^^
SyntaxError: cannot assign to expression here. Maybe you meant '=='
instead of '='?
42
Python Basic
Though z=x+y and x+y=z are equivalent in Mathematics, it is not so here. It's
because = is an equation symbol, while in Python it is an assignment operator.
Multiple Assignments
In Python, you can initialize more than one variables in a single statement. In
the following case, three variables have same value.
>>> a=10
>>> b=10
>>> c=10
Instead of separate assignments, you can do it in a single assignment statement
as follows −
>>> a=b=c=10
>>> print (a,b,c)
10 10 10
In the following case, we have three variables with different values.
>>> a=10
>>> b=20
>>> c=30
These separate assignment statements can be combined in one. You need to
give comma separated variable names on left, and comma separated values on
the right of = operator.
>>> a,b,c = 10,20,30
>>> print (a,b,c)
10 20 30
The concept of variable works differently in Python than in C/C++.
In C/C++, a variable is a named memory location. If a=10 and also b=10, both
are two different memory locations. Let us assume their memory address is 100
and 200 respectively.
43
Python Basic
A Python variable refers to the object and not the memory location. An object is
stored in memory only once. Multiple variables are really the multiple labels to
the same object.
The statement a=50 creates a new int object 50 in the memory at some other
location, leaving the object 10 referred by "b".
Further, if you assign some other value to b, the object 10 remains unreferred.
Python's data model defines four main data types. They are Number, Sequence,
Set and Dictionary (also called Mapping)
Number Type
Any data item having a numeric value is a number. There are Four standard
number data types in Python. They are integer, floating point, Boolean and
Complex. Each of them have built-in classes in Python library, called int, float,
bool and complex respectively.
45
Python Basic
46
Python Basic
47
Python Basic
LIST IN PYTHON
In Python, List is an ordered collection of any type of data items. Data items are
separated by comma (,) symbol and enclosed in square brackets ([]). A list is
also a sequence, hence.
each item in the list has an index referring to its position in the collection. The
index starts from 0.
The list in Python appears to be similar to array in C or C++. However, there is
an important difference between the two. In C/C++, array is a homogenous
collection of data of similar types. Items in the Python list may be of different
types.
>>> [2023, "Python", 3.11, 5+6j, 1.23E-4]
A list in Python is an object of list class. We can check it with type() function.
>>> type([2023, "Python", 3.11, 5+6j, 1.23E-4])
<class 'list'>
As mentioned, an item in the list may be of any data type. It means that a list
object can also be an item in another list. In that case, it becomes a nested list.
>>> [['One', 'Two', 'Three'], [1,2,3], [1.0, 2.0, 3.0]]
A list item may be a tuple, dictionary, set or object of user defined class also.
List being a sequence, it supports slicing and concatenation operations as in
case of string. With the methods/functions available in Python's built-in list
class, we can add, delete or update items, and sort or rearrange the items in the
desired order. We shall study these aspects in a subsequent chapter.
Tuples in Python
In Python, a Tuple is an ordered collection of any type of data items. Data items
are separated by comma (,) symbol and enclosed in parentheses or round
brackets (). A tuple is also a sequence, hence each item in the tuple has an index
referring to its position in the collection. The index starts from 0.
>>> (2023, "Python", 3.11, 5+6j, 1.23E-4)
In Python, a tuple is an object of tuple class. We can check it with the type()
function.
>>> type((2023, "Python", 3.11, 5+6j, 1.23E-4))
<class 'tuple'>
As in case of a list, an item in the tuple may also be a list, a tuple itself or an
object of any other Python class.
>>> (['One', 'Two', 'Three'], 1,2.0,3, (1.0, 2.0, 3.0))
To form a tuple, use of parentheses is optional. Data items separated by comma
without any enclosing symbols are treated as a tuple by default.
48
Python Basic
49
Python Basic
DICTIONARY TYPE
Python's dictionary is example of mapping type. A mapping object 'maps' value
of one object with another. In a language dictionary we have pairs of word and
corresponding meaning. Two parts of pair are key (word) and value (meaning).
Similarly, Python dictionary is also a collection of key:value pairs. The pairs
are separated by comma and put inside curly brackets {}. To establish mapping
between key and value, the semicolon':' symbol is put between the two.
>>> {1:'one', 2:'two', 3:'three'}
Each key in a dictionary must be unique, and should be a number, string or
tuple. The value object may be of any type, and may be mapped with more than
one keys (they need not be unique)
In Python, dictionary is an object of the built-in dict class. We can check it with
the type() function.
>>> type({1:'one', 2:'two', 3:'three'})
<class 'dict'>
Python's dictionary is not a sequence. It is a collection of items but each item
(key:value pair) is not identified by positional index as in string, list or tuple.
Hence, slicing operation cannot be done on a dictionary. Dictionary is a mutable
object, so it is possible to perform add, modify or delete actions with
corresponding functionality defined in dict class. These operations will be
explained in a subsequent chapter.
Set Type
Set is a Python implementation of set as defined in Mathematics. A set in
Python is a collection, but is not an indexed or ordered collection as string, list
or tuple. An object cannot appear more than once in a set, whereas in List and
Tuple, same object can appear more than once.
Comma separated items in a set are put inside curly brackets or braces. Items in
the set collection may be of different data types.
>>> {2023, "Python", 3.11, 5+6j, 1.23E-4}
{(5+6j), 3.11, 0.000123, 'Python', 2023}
Note that items in the set collection may not follow the same order in which
they are entered. The position of items is optimized by Python to perform
operations over set as defined in mathematics.
Python's Set is an object of built-in set class, as can be checked with the type()
function.
>>> type({2023, "Python", 3.11, 5+6j, 1.23E-4})
<class 'set'>
50
Python Basic
A set can store only immutable objects such as number (int, float, complex or
bool), string or tuple. If you try to put a list or a dictionary in the set collection,
Python raises a TypeError.
>>> {['One', 'Two', 'Three'], 1,2,3, (1.0, 2.0, 3.0)}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Hashing is a mechanism in computer science which enables quicker searching
of objects in computer's memory. Only immutable objects are hashable.
Even if a set doesn't allow mutable items, the set itself is mutable. Hence,
add/delete/update operations are permitted on a set object, using the methods in
built-in set class. Python also has a set of operators to perform set manipulation.
The methods and operators are explained in a latter chapter
Python - Type Casting
In manufacturing, casting is the process of pouring a liquefied or molten metal
into a mold, and letting it cool to obtain the desired shape. In programming,
casting refers to converting an object of one type into another. Here, we shall
learn about type casting in Python.
In Python there are different data types, such as numbers, sequences, mappings
etc. There may be a situation where, you have the available data of one type but
you want to use it in another form. For example, the user has input a string but
you want to use it as a number. Python's type casting mechanism let you do that.
Implicit Casting in Python
Casting is of two types − implicit and explicit.
When any language compiler/interpreter automatically converts object of one
type into other, it is called implicit casting. Python is a strongly typed language.
It doesn't allow automatic type conversion between unrelated data types. For
example, a string cannot be converted to any number type. However, an integer
can be cast into a float. Other languages such as JavaScript is a weakly typed
language, where an integer is coerced into a string for concatenation.
Note that memory requirement of each type is different. For example, an integer
object in Python occupies 4 bytes of memory, while a float object needs 8 bytes
because of its fractional part. Hence, Python interpreter doesn't automatically
convert a float to int, because it will result in loss of data. On the other hand, int
can be easily converted into float by setting its fractional part to 0.
Implicit int to float casting takes place when any arithmetic operation one int
and float operands is done.
51
Python Basic
52
Python Basic
53
Python Basic
54
Python Basic
>>> type(a)
<class 'float'>
is same as −
>>> a = 9.99
>>> a
9.99
>>> type(a)
<class 'float'>
If the argument to float() function is an integer, the returned value is a floating
point with fractional part set to 0.
>>> a = float(100)
>>> a
100.0
>>> type(a)
<class 'float'>
The float() function returns float object from a string, if the string contains a
valid floating point number, otherwise ValueError is raised.
>>> a = float("9.99")
>>> a
9.99
>>> type(a)
<class 'float'>
>>> a = float("1,234.50")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '1,234.50'
The reason of ValueError here is the presence of comma in the string.
For the purpose of string to float conversion, the sceientific notation of floating
point is also considered valid.
>>> a = float("1.00E4")
>>> a
10000.0
>>> type(a)
<class 'float'>
>>> a = float("1.00E-4")
>>> a
0.0001
55
Python Basic
>>> type(a)
<class 'float'>
str() Function
We saw how a Python obtains integer or float number from corresponding
string representation. The str() function works the opposite. It surrounds an
integer or a float object with quotes (') to return a str object. The str() function
returns the string.
representation of any Python object. In this section, we shall see different
examples of str() function in Python.
The str() function has three parameters. First required parameter (or argument)
is the object whose string representation we want. Other two operators,
encoding and errors, are optional.
We shall execute str() function in Python console to easily verify that the
returned object is a string, with the enclosing quotation marks (').
Integer to string
>>> a = str(10)
>>> a
'10'
>>> type(a)
<class 'str'>
Float to String
str() function converts floating point objects with both the notations of floating
point, standard notation with a decimal point separating integer and fractional
part, and the scientific notation to string object.
>>> a=str(11.10)
>>> a
'11.1'
>>> type(a)
<class 'str'>
>>> a = str(2/5)
>>> a
'0.4'
>>> type(a)
<class 'str'>
In the second case, a division expression is given as argument to str() function.
Note that the expression is evaluated first and then result is converted to string.
56
Python Basic
57
Python Basic
### list() separates each character in the string and builds the list
>>> obj=list(c)
>>> obj
['H', 'e', 'l', 'l', 'o']
### The parentheses of tuple are replaced by square brackets
>>> obj=list(b)
>>> obj
[1, 2, 3, 4, 5]
### tuple() separates each character from string and builds a tuple of
characters
>>> obj=tuple(c)
>>> obj
('H', 'e', 'l', 'l', 'o')
### square brackets of list are replaced by parentheses.
>>> obj=tuple(a)
>>> obj
(1, 2, 3, 4, 5)
### str() function puts the list and tuple inside the quote symbols.
>>> obj=str(a)
>>> obj
'[1, 2, 3, 4, 5]'
>>> obj=str(b)
>>> obj
'(1, 2, 3, 4, 5)'
Thus Python's explicit type casting feature allows conversion of one data type to
other with the help of its built-in functions.
58
Python Basic
CHAPTER -3
PYTHON - UNICODE SYSTEM
Software applications often require to display messages output in a variety in
different languages such as in English, French, Japanese, Hebrew, or Hindi.
Python's string type uses the Unicode Standard for representing characters. It
makes the program possible to work with all these different possible characters.
A character is the smallest possible component of a text. 'A', 'B', 'C', etc., are all
different characters. So are 'È' and 'Í'.
According to The Unicode standard, characters are represented by code points.
A code point value is an integer in the range 0 to 0x10FFFF.
A sequence of code points is represented in memory as a set of code units,
mapped to 8-bit bytes. The rules for translating a Unicode string into a sequence
of bytes are called a character encoding.
Three types of encodings are present, UTF-8, UTF-16 and UTF-32. UTF stands
for Unicode Transformation Format.
Python 3.0 onwards has built-in support for Unicode. The str type contains
Unicode characters, hence any string created using single, double or the triple-
quoted string syntax is stored as Unicode. The default encoding for Python
source code is UTF-8.
Hence, string may contain literal representation of a Unicode character (3/4) or
its Unicode value (\u00BE).
var = "3/4"
print (var)
var = "\u00BE"
print (var)
This above code will produce the following output −
'3/4'
3/4
In the following example, a string '10' is stored using the Unicode values of 1
and 0 which are \u0031 and u0030 respectively.
var = "\u0031\u0030"
print (var)
It will produce the following output −
10
Strings display the text in a human-readable format, and bytes store the
characters as binary data. Encoding converts data from a character string to a
59
Python Basic
PYTHON - LITERALS
In computer science, a literal is a notation for representing a fixed value in
source code. For example, in the assignment statement.
x = 10
Here 10 is a literal as numeric value representing 10 is directly stored in
memory. However,
y = x*2
60
Python Basic
Here, even if the expression evaluates to 20, it is not literally included in source
code. You can also declare an int object with built-in int() function −
x = int(10)
However, this is also an indirect way of instantiation and not with literal.
You can create use literal representation for creating object of any built-in data
type.
Integer Literal
Any representation involving only the digit symbols (0 to 9) creates an object of
int type. The object so declared may be referred by a variable using an
assignment operator.
Take a look at the following example −
x = 10
y = -25
z=0
Python allows an integer to be represented as an octal number or a hexadecimal
number. A numeric representation with only eight digit symbols (0 to 7) but
prefixed by 0o or 0O is an octal number.
x = 0O34
Similarly, a series of hexadecimal symbols (0 to 9 and a to f), prefixed by 0x or
0X represents an integer in Hexedecimal form.
x = 0X1C
However, it may be noted that, even if you use octal or hexadecimal literal
notation, Python internally treats it as of int type.
# Using Octal notation
x = 0O34
print ("0O34 in octal is", x, type(x))
# Using Hexadecimal notation
x = 0X1c
print ("0X1c in Hexadecimal is", x, type(x))
When you run this code, it will produce the following output −
0O34 in octal is 28 <class 'int'>
0X1c in Hexadecimal is 28 <class 'int'>
Float Literal
A floating point number consists of an integral part and a fractional part.
Conventionally, a decimal point symbol (.) separates these two parts in a literal
representation of a float. For example,
x = 25.55
61
Python Basic
y = 0.05
z = -12.2345
For a floating point number which is too large or too small, where number of
digits before or after decimal point is more, a scientific notation is used for a
compact literal representation. The symbol E or e followed by positive or
negative integer, follows after the integer part.
For example, a number 1.23E05 is equivalent to 123000.00. Similarly, 1.23e-2
is equivalent to 0.0123
# Using normal floating point notation
x = 1.23
print ("1.23 in normal float literal is", x, type(x))
# Using Scientific notation
x = 1.23E5
print ("1.23E5 in scientific notation is", x, type(x))
x = 1.23E-2
print ("1.23E-2 in scientific notation is", x, type(x))
Here, you will get the following output −
1.23 in normal float literal is 1.23 <class 'float'>
1.23E5 in scientific notation is 123000.0 <class 'float''>
1.23E-2 in scientific notation is 0.0123 <class 'float''>
COMPLEX LITERAL
A complex number comprises of a real and imaginary component. The
imaginary component is any number (integer or floating point) multiplied by
square root of "-1"
(−1−−−√
). In literal representation (−1−−−√
) is representation by "j" or "J". Hence, a literal representation of a complex
number takes a form x+yj.
#Using literal notation of complex number
x = 2+3j
print ("2+3j complex literal is", x, type(x))
y = 2.5+4.6j
print ("2.5+4.6j complex literal is", x, type(x))
This code will produce the following output −
2+3j complex literal is (2+3j) <class 'complex'>
2.5+4.6j complex literal is (2+3j) <class 'complex'>
62
Python Basic
String Literal
A string object is one of the sequence data types in Python. It is an immutable
sequence of Unicode code points. Code point is a number corresponding to a
character according to Unicode standard. Strings are objects of Python's built-in
class 'str'.
String literals are written by enclosing a sequence of characters in single quotes
('hello'), double quotes ("hello") or triple quotes ('''hello''' or """hello""").
var1='hello'
print ("'hello' in single quotes is:", var1, type(var1))
var2="hello"
print ('"hello" in double quotes is:', var1, type(var1))
var3='''hello'''
print ("''''hello'''' in triple quotes is:", var1, type(var1))
var4="""hello"""
print ('"""hello""" in triple quotes is:', var1, type(var1))
Here, you will get the following output −
'hello' in single quotes is: hello <class 'str'>
"hello" in double quotes is: hello <class 'str'>
''''hello'''' in triple quotes is: hello <class 'str'>
"""hello""" in triple quotes is: hello <class 'str'>
If it is required to embed double quotes as a part of string, the string itself
should be put in single quotes. On the other hand, if single quoted text is to be
embedded, string should be written in double quotes.
var1='Welcome to "Python Tutorial" from TutorialsPoint'
print (var1)
var2="Welcome to 'Python Tutorial' from TutorialsPoint"
print (var2)
It will produce the following output −
Welcome to "Python Tutorial" from TutorialsPoint
Welcome to 'Python Tutorial' from TutorialsPoint
List Literal
List object in Python is a collection of objects of other data type. List is an
ordered collection of items not necessarily of same type. Individual object in the
collection is accessed by index starting with zero.
Literal representation of a list object is done with one or more items which are
separated by comma and enclosed in square brackets [].
L1=[1,"Ravi",75.50, True]
63
Python Basic
64
Python Basic
65
Python Basic
66
Python Basic
67
Python Basic
b=6.75E-3
print ("Multiplication of float and float")
print ("a =",a,"b =",b,"a*b =",a*b)
It will produce the following output −
Multiplication of integer and float
a = 10 b = 20.5 a-b = -10.5
Multiplication of float and float
a = -5.55 b = 0.00675 a*b = -0.037462499999999996
For the multiplication operation involving one complex operand, the other
operand multiplies both the real part and imaginary part.
a=10+5j
b=20.5
print ("Multiplication of complex and float")
print ("a =",a,"b =",b,"a*b =",a*b)
It will produce the following output −
Multiplication of complex and float
a = (10+5j) b = 20.5 a*b = (205+102.5j)
Python − Division Operator (/)
The "/" symbol is usually called as forward slash. The result of division operator
is numerator (left operand) divided by denominator (right operand). The
resultant number is negative if any of the operands is negative. Since infinity
cannot be stored in the memory, Python raises ZeroDivisionError if the
denominator is 0.
The result of division operator in Python is always a float, even if both operands
are integers.
a=10
b=20
print ("Division of two integers")
print ("a=",a,"b=",b,"a/b=",a/b)
print ("a=",a,"b=",b,"b/a=",b/a)
It will produce the following output −
Division of two integers
a= 10 b= 20 a/b= 0.5
a= 10 b= 20 b/a= 2.0
In Division, a float operand may have a standard decimal point notation, or a
scientific notation.
a=10
68
Python Basic
b=-20.5
print ("Division of integer and float")
print ("a=",a,"b=",b,"a/b=",a/b)
a=-2.50
b=1.25E2
print ("Division of float and float")
print ("a=",a,"b=",b,"a/b=",a/b)
It will produce the following output −
Division of integer and float
a= 10 b= -20.5 a/b= -0.4878048780487805
Division of float and float
a= -2.5 b= 125.0 a/b= -0.02
When one of the operands is a complex number, division between the other
operand and both parts of complex number (real and imaginary) object takes
place.
a=7.5+7.5j
b=2.5
print ("Division of complex and float")
print ("a =",a,"b =",b,"a/b =",a/b)
print ("a =",a,"b =",b,"b/a =",b/a)
It will produce the following output −
Division of complex and float
a = (7.5+7.5j) b = 2.5 a/b = (3+3j)
a = (7.5+7.5j) b = 2.5 b/a = (0.16666666666666666-0.16666666666666666j)
If the numerator is 0, the result of division is always 0 except when denominator
is 0, in which case, Python raises ZeroDivisionError wirh Division by Zero
error message.
a=0
b=2.5
print ("a=",a,"b=",b,"a/b=",a/b)
print ("a=",a,"b=",b,"b/a=",b/a)
It will produce the following output −
a= 0 b= 2.5 a/b= 0.0
Traceback (most recent call last):
File "C:\Users\mlath\examples\example.py", line 20, in <module>
print ("a=",a,"b=",b,"b/a=",b/a)
~^~
69
Python Basic
70
Python Basic
a=10
b=1.5
print ("a=",a, "b=",b, "a%b=", a%b)
a=7.7
b=2.5
print ("a=",a, "b=",b, "a%b=", a%b)
a=12.4
b=3
print ("a=",a, "b=",b, "a%b=", a%b)
It will produce the following output −
a= 10 b= 2.5 a%b= 0.0
a= 10 b= 1.5 a%b= 1.0
a= 7.7 b= 2.5 a%b= 0.20000000000000018
a= 12.4 b= 3 a%b= 0.40000000000000036
Python doesn't accept complex numbers to be used as operand in modulus
operation. It throws TypeError: unsupported operand type(s) for %.
Python − Exponent Operator (**)
Python uses ** (double asterisk) as the exponent operator (sometimes called
raised to operator). So, for a**b, you say a raised to b, or even bth power of a.
If in the exponentiation expression, both operands are integer, result is also an
integer. In case either one is a float, the result is float. Similarly, if either one
operand is complex number, exponent operator returns a complex number.
If the base is 0, the result is 0, and if the index is 0 then the result is always 1.
a=10
b=2
print ("a=",a, "b=",b, "a**b=", a**b)
a=10
b=1.5
print ("a=",a, "b=",b, "a**b=", a**b)
a=7.7
b=2
print ("a=",a, "b=",b, "a**b=", a**b)
a=1+2j
b=4
print ("a=",a, "b=",b, "a**b=", a**b)
a=12.4
b=0
71
Python Basic
72
Python Basic
73
Python Basic
b=3+2j
c=a/b
c=(6+4j)/(3+2j)
c=(6+4j)*(3-2j)/3+2j)*(3-2j)
c=(18-12j+12j+8)/(9-6j+6j+4)
c=26/13
c=2+0j
To verify, run the following code −
a=6+4j
b=3+2j
print ("Division of complex numbers - a=",a, "b=",b, "a/b=", a/b)
Complex class in Python doesn't support the modulus operator (%) and floor
division operator (//).
Python - Assignment Operators
The = (equal to) symbol is defined as assignment operator in Python. The value
of Python expression on its right is assigned to a single variable on its left. The
= symbol as in programming in general (and Python in particular) should not be
confused with its usage in Mathematics, where it states that the expressions on
the either side of the symbol are equal.
In addition to the simple assignment operator, Python provides few more
assignment operators for advanced use. They are called cumulative or
augmented assignment operators. In this chapter, we shall learn to use
augmented assignment operators defined in Python.
Consider following Python statements −
a=10
b=5
a=a+b
print (a)
At the first instance, at least for somebody new to programming but who knows
maths, the statement "a=a+b" looks strange. How could a be equal to "a+b"?
However, it needs to be reemphasized that the = symbol is an assignment
operator here and not used to show the equality of LHS and RHS.
Because it is an assignment, the expression on right evaluates to 15, the value is
assigned to a.
In the statement "a+=b", the two operators "+" and "=" can be combined in a
"+=" operator. It is called as add and assign operator. In a single statement, it
74
Python Basic
performs addition of two operands "a" and "b", and result is assigned to operand
on left, i.e., "a".
The += operator is an augmented operator. It is also called cumulative addition
operator, as it adds "b" in "a" and assigns the result back to a variable.
Python has the augmented assignment operators for all arithmetic and
comparison operators.
Python - Augmented Addition Operator (+=)
This operator combines addition and assignment in one statement. Since Python
supports mixed arithmetic, the two operands may be of different types.
However, the type of left operand changes to the operand of on right, if it is
wider.
Following examples will help in understanding how the "+=" operator works −
a=10
b=5
print ("Augmented addition of int and int")
a+=b #equivalent to a=a+b
print ("a=",a, "type(a):", type(a))
a=10
b=5.5
print ("Augmented addition of int and float")
a+=b #equivalent to a=a+b
print ("a=",a, "type(a):", type(a))
a=10.50
b=5+6j
print ("Augmented addition of float and complex")
a+=b #equivalent to a=a+b
print ("a=",a, "type(a):", type(a))
It will produce the following output −
Augmented addition of int and int
a= 15 type(a): <class 'int'>
Augmented addition of int and float
a= 15.5 type(a): <class 'float'>
Augmented addition of float and complex
a= (15.5+6j) type(a): <class 'complex'>
Python − Augmented Subtraction Operator (-=)
Use -= symbol to perform subtract and assign operations in a single statement.
The "a-=b" statement performs "a=a-b" assignment. Operands may be of any
75
Python Basic
number type. Python performs implicit type casting on the object which is
narrower in size.
a=10
b=5
print ("Augmented subtraction of int and int")
a-=b #equivalent to a=a-b
print ("a=",a, "type(a):", type(a))
a=10
b=5.5
print ("Augmented subtraction of int and float")
a-=b #equivalent to a=a-b
print ("a=",a, "type(a):", type(a))
a=10.50
b=5+6j
print ("Augmented subtraction of float and complex")
a-=b #equivalent to a=a-b
print ("a=",a, "type(a):", type(a))
It will produce the following output −
Augmented subtraction of int and int
a= 5 type(a): <class 'int'>
Augmented subtraction of int and float
a= 4.5 type(a): <class 'float'>
Augmented subtraction of float and complex
a= (5.5-6j) type(a): <class 'complex'>
76
Python Basic
77
Python Basic
78
Python Basic
a=6+4j
b=3+2j
print ("Augmented exponent operator with complex and complex")
a**=b #equivalent to a=a**b
print ("a=",a, "type(a):", type(a))
It will produce the following output −
Augmented exponent operator with int and int
a= 100000 type(a): <class 'int'>
Augmented exponent operator with int and float
a= 316227.7660168379 type(a): <class 'float'>
Augmented exponent operator with complex and complex
a= (97.52306038414744-62.22529992036203j) type(a): <class 'complex'>
Python − Augmented Floor division Operator (//=)
For performing floor division and assignment in a single statement, use the "//="
operator. "a//=b" is equivalent to "a=a//b". This operator cannot be used with
complex numbers.
a=10
b=5
print ("Augmented floor division operator with int and int")
a//=b #equivalent to a=a//b
print ("a=",a, "type(a):", type(a))
a=10
b=5.5
print ("Augmented floor division operator with int and float")
a//=b #equivalent to a=a//b
print ("a=",a, "type(a):", type(a))
It will produce the following output −
Augmented floor division operator with int and int
a= 2 type(a): <class 'int'>
Augmented floor division operator with int and float
a= 1.0 type(a): <class 'float'>
Python - Comparison Operators
Comparison operators in Python are very important in Python's conditional
statements (if, else and elif) and looping statements (while and for loops). Like
arithmetic operators, the comparison operators "-" also called relational
operators, ("<" stands for less than, and">" stands for greater than) are well
known.
79
Python Basic
Python uses two more operators, combining "=" symbol with these two. The
"<=" symbol is for less than or equal to. The ">=" symbol is for greater than or
equal to.
Python has two more comparison operators in the form of "==" and "!=". They
are for is equal to and is not equal to operators. Hence, there are six comparison
operators in Python.
< Less than a<b
> Greater than a>b
<= Less than or equal to a<=b
>= Greater than or equal to a>=b
== Is equal to a==b
!= Is not equal to a!=b
Comparison operators are binary in nature, requiring two operands. An
expression involving a comparison operator is called a Boolean expression, and
always returns either True or False.
a=5
b=7
print (a>b)
print (a<b)
It will produce the following output −
False
True
Both the operands may be Python literals, variables or expressions. Since
Python supports mixed arithmetic, you can have any number type operands.
The following code demonstrates the use of Python's comparison operators
with integer numbers −
print ("Both operands are integer")
a=5
b=7
print ("a=",a, "b=",b, "a>b is", a>b)
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)
It will produce the following output −
Both operands are integer
a= 5 b= 7 a>b is False
a= 5 b= 7 a<b is True
80
Python Basic
a= 5 b= 7 a==b is False
a= 5 b= 7 a!=b is True
Comparison of Float Number
In the following example, an integer and a float operand are compared.
print ("comparison of int and float")
a=10
b=10.0
print ("a=",a, "b=",b, "a>b is", a>b)
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)
It will produce the following output −
comparison of int and float
a= 10 b= 10.0 a>b is False
a= 10 b= 10.0 a<b is False
a= 10 b= 10.0 a==b is True
a= 10 b= 10.0 a!=b is False
Comparison of Complex umbers
Although complex object is a number data type in Python, its behavior is
different from others. Python doesn't support < and > operators, however it does
support equality (==) and inequality (!=) operators.
print ("comparison of complex numbers")
a=10+1j
b=10.-1j
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)
It will produce the following output −
comparison of complex numbers
a= (10+1j) b= (10-1j) a==b is False
a= (10+1j) b= (10-1j) a!=b is True
You get a TypeError with less than or greater than operators.
print ("comparison of complex numbers")
a=10+1j
b=10.-1j
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a>b is",a>b)
It will produce the following output −
81
Python Basic
82
Python Basic
^^^
TypeError: '<' not supported between instances of 'tuple' and 'list'
Sequence objects are compared by lexicographical ordering mechanism. The
comparison starts from item at 0th index. If they are equal, comparison moves
to next index till the items at certain index happen to be not equal, or one of the
sequences is exhausted. If one sequence is an initial sub-sequence of the other,
the shorter sequence is the smaller (lesser) one.
Which of the operands is greater depends on the difference in values of items at
the index where they are unequal. For example, 'BAT'>'BAR' is True, as T
comes after R in Unicode order.
If all items of two sequences compare equal, the sequences are considered
equal.
print ("comparison of strings")
a='BAT'
b='BALL'
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a>b is",a>b)
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)
It will produce the following output −
comparison of strings
a= BAT b= BALL a<b is False
a= BAT b= BALL a>b is True
a= BAT b= BALL a==b is False
a= BAT b= BALL a!=b is True
In the following example, two tuple objects are compared −
print ("comparison of tuples")
a=(1,2,4)
b=(1,2,3)
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a>b is",a>b)
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)
It will produce the following output −
a= (1, 2, 4) b= (1, 2, 3) a<b is False
a= (1, 2, 4) b= (1, 2, 3) a>b is True
a= (1, 2, 4) b= (1, 2, 3) a==b is False
83
Python Basic
84
Python Basic
TTT
The "or" Operator
In contrast, the or operator returns True if any of the operands is True. For the
compound Boolean expression to be False, both the operands have to be False,
ss the following table shows −
a b a or b
FFF
F TT
TFF
TTT
The "not" Operator
This is a unary operator. The state of Boolean operand that follows, is reversed.
As a result, not True becomes False and not False becomes True.
a not (a)
FT
TF
How the Python interpreter evaluates the logical operators?
The expression "x and y" first evaluates "x". If "x" is false, its value is returned;
otherwise, "y" is evaluated and the resulting value is returned.
The expression "x or y" first evaluates "x"; if "x" is true, its value is returned;
otherwise, "y" is evaluated and the resulting value is returned.
85
Python Basic
86
Python Basic
87
Python Basic
0 & 0 is 0
1 & 0 is 0
0 & 1 is 0
1 & 1 is 1
When you use integers as the operands, both are converted in equivalent binary,
the & operation is done on corresponding bit from each number, starting from
the least significant bit and going towards most significant bit.
Let us take two integers 60 and 13, and assign them to variables a and b
respectively.
a=60
b=13
print ("a:",a, "b:",b, "a&b:",a&b)
It will produce the following output −
a: 60 b: 13 a&b: 12
To understand how Python performs the operation, obtain the binary equivalent
of each variable.
print ("a:", bin(a))
print ("b:", bin(b))
It will produce the following output −
a: 0b111100
b: 0b1101
For the sake of convenience, use the standard 8-bit format for each number, so
that "a" is 00111100 and "b" is 00001101. Let us manually perform and
operation on each corresponding bits of these two numbers.
0011 1100
&
0000 1101
-------------
0000 1100
Convert the resultant binary back to integer. You'll get 12, which was the result
obtained earlier.
>>> int('00001100',2)
12
Python − Bitwise OR Operator (|)
The "|" symbol (called pipe) is the bitwise OR operator. If any bit operand is 1,
the result is 1 otherwise it is 0.
0 | 0 is 0
88
Python Basic
0 | 1 is 1
1 | 0 is 1
1 | 1 is 1
Take the same values of a=60, b=13. The "|" operation results in 61. Obtain
their binary equivalents.
a=60
b=13
print ("a:",a, "b:",b, "a|b:",a|b)
print ("a:", bin(a))
print ("b:", bin(b))
It will produce the following output −
a: 60 b: 13 a|b: 61
a: 0b111100
b: 0b1101
To perform the "|" operation manually, use the 8-bit format.
0011 1100
|
0000 1101
-------------
0011 1101
Convert the binary number back to integer to tally the result −
>>> int('00111101',2)
61
Python − Binary XOR Operator (^)
The term XOR stands for exclusive OR. It means that the result of OR operation
on two bits will be 1 if only one of the bits is 1.
0 ^ 0 is 0
0 ^ 1 is 1
1 ^ 0 is 1
1 ^ 1 is 0
Let us perform XOR operation on a=60 and b=13.
a=60
b=13
print ("a:",a, "b:",b, "a^b:",a^b)
It will produce the following output −
a: 60 b: 13 a^b: 49
We now perform the bitwise XOR manually.
89
Python Basic
0011 1100
^
0000 1101
-------------
0011 0001
The int() function shows 00110001 to be 49.
>>> int('00110001',2)
49
90
Python Basic
-------------
1111 0000
Convert the binary to integer. It is 240.
>>> int('11110000',2)
240
Python − Right Shift Operator (>>)
Right shift operator shifts least significant bits to left by the number on the right
side of the ">>" symbol. Hence, "x >> 2" causes two bits of the binary
representation of to left. Let us perform right shift on 60.
a=60
print ("a:",a, "a>>2:", a>>2)
It will produce the following output −
a: 60 a>>2: 15
Manual right shift operation on 60 is shown below −
0011 1100
>>
2
-------------
0000 1111
Use int() function to covert the above binary number to integer. It is 15.
>>> int('00001111',2)
15
Python - Membership Operators
The membership operators in Python help us determine whether an item is
present in a given container type object, or in other words, whether an item is a
member of the given container type object.
Python has two membership operators: "in" and "not in". Both return a Boolean
result. The result of "in" operator is opposite to that of "not in" operator.
You can use in operator to check whether a substring is present in a bigger
string, any item is present in a list or tuple, or a sub-list or sub-tuple is included
in a list or tuple.
In the following example, different substrings are checked whether they belong
to the string var="TutorialsPoint". Python differentiates characters on the basis
of their Unicode value. Hence "To" is not the same as "to". Also note that if the
"in" operator returns True, the "not in" operator evaluates to False.
var = "TutorialsPoint"
a = "P"
91
Python Basic
b = "tor"
c = "in"
d = "To"
print (a, "in", var, ":", a in var)
print (b, "not in", var, ":", b not in var)
print (c, "in", var, ":", c in var)
print (d, "not in", var, ":", d not in var)
It will produce the following output −
P in TutorialsPoint : True
tor not in TutorialsPoint : False
in in TutorialsPoint : True
To not in TutorialsPoint : True
You can use the "in/not in" operator to check the membership of an item in the
list or tuple.
var = [10,20,30,40]
a = 20
b = 10
c = a-b
d = a/2
print (a, "in", var, ":", a in var)
print (b, "not in", var, ":", b not in var)
print (c, "in", var, ":", c in var)
print (d, "not in", var, ":", d not in var)
It will produce the following output −
20 in [10, 20, 30, 40] : True
10 not in [10, 20, 30, 40] : False
10 in [10, 20, 30, 40] : True
10.0 not in [10, 20, 30, 40] : False
In the last case, "d" is a float but still it compares to True with 10 (an int) in the
list. Even if a number expressed in other formats like binary, octal or
hexadecimal are given the membership operators tell if it is inside the sequence.
>>> 0x14 in [10, 20, 30, 40]
True
However, if you try to check if two successive numbers are present in a list or
tuple, the in operator returns False. If the list/tuple contains the successive
numbers as a sequence itself, then it returns True.
var = (10,20,30,40)
92
Python Basic
a = 10
b = 20
print ((a,b), "in", var, ":", (a,b) in var)
var = ((10,20),30,40)
a = 10
b = 20
print ((a,b), "in", var, ":", (a,b) in var)
It will produce the following output −
(10, 20) in (10, 20, 30, 40) : False
(10, 20) in ((10, 20), 30, 40) : True
Python's membership operators also work well with the set objects.
var = {10,20,30,40}
a = 10
b = 20
print (b, "in", var, ":", b in var)
var = {(10,20),30,40}
a = 10
b = 20
print ((a,b), "in", var, ":", (a,b) in var)
It will produce the following output −
20 in {40, 10, 20, 30} : True
(10, 20) in {40, 30, (10, 20)} : True
Use of in as well as not in operators with dictionary object is allowed. However,
Python checks the membership only with the collection of keys and not values.
var = {1:10, 2:20, 3:30}
a=2
b = 20
print (a, "in", var, ":", a in var)
print (b, "in", var, ":", b in var)
It will produce the following output −
2 in {1: 10, 2: 20, 3: 30} : True
20 in {1: 10, 2: 20, 3: 30} : False
Python - Identity Operators
Python has two identity operators is and is not. Both return opposite Boolean
values. The "in" operator evaluates to True if both the operand objects share the
same memory location. The memory location of the object can be obtained by
93
Python Basic
the "id()" function. If the id() of both variables is same, the "in" operator returns
True (as a consequence, is not returns False).
a="TutorialsPoint"
b=a
print ("id(a), id(b):", id(a), id(b))
print ("a is b:", a is b)
print ("b is not a:", b is not a)
It will produce the following output −
id(a), id(b): 2739311598832 2739311598832
a is b: True
b is not a: False
The list and tuple objects differently, which might look strange in the first
instance. In the following example, two lists "a" and "b" contain same items.
But their id() differs.
a=[1,2,3]
b=[1,2,3]
print ("id(a), id(b):", id(a), id(b))
print ("a is b:", a is b)
print ("b is not a:", b is not a)
It will produce the following output −
id(a), id(b): 1552612704640 1552567805568
a is b: False
b is not a: True
The list or tuple contains the memory locations of individual items only and not
the items itself. Hence "a" contains the addresses of 10,20 and 30 integer objects
in a certain location which may be different from that of "b".
print (id(a[0]), id(a[1]), id(a[2]))
print (id(b[0]), id(b[1]), id(b[2]))
It will produce the following output −
140734682034984 140734682035016 140734682035048
140734682034984 140734682035016 140734682035048
Because of two different locations of "a" and "b", the "is" operator returns False
even if the two lists contain same numbers.
Python - Comments
A comment in a computer program is a piece of text that is meant to be an
explanatory or descriptive annotation in the source code and is not to be
considered by compiler/interpreter while generating machine language code.
94
Python Basic
95
Python Basic
city = "Hyderabad"
print ("Hello My name is", name)
print ("I am from", city)
Save the above code as hello.py and run it from the command-line. Here's the
output
C:\python311> python var1.py
Hello My name is Kiran
I am from Hyderabad
The program simply prints the values of the two variables in it. If you run the
program repeatedly, the same output will be displayed every time. To use the
program for another name and city, you can edit the code, change name to say
"Ravi" and city to "Chennai". Every time you need to assign different value,
you will have to edit the program, save and run, which is not the ideal way.
input() Function
Obviously, you need some mechanism to assign different value to the variable
in the runtime − while the program is running. Python's input() function does
the same job.
Python's standard library has the input() function.
>>> var = input()
When the interpreter encounters it, it waits for the user to enter data from the
standard input stream (keyboard) till the Enter key is pressed. The sequence of
characters may be stored in a string variable for further use.
On reading the Enter key, the program proceeds to the next statement. Let use
change our program to store the user input in name and city variables.
#! /usr/bin/python3.11
name = input()
city = input()
print ("Hello My name is", name)
print ("I am from ", city)
When you run, you will find the cursor waiting for user's input. Enter values for
name and city. Using the entered data, the output will be displayed.
Ravi
Chennai
Hello My name is Ravi
I am from Chennai
96
Python Basic
Now, the variables are not assigned any specific value in the program. Every
time you run, different values can be input. So, your program has become truly
interactive.
Inside the input() function, you may give a prompt text, which will appear
before the cursor when you run the code.
#! /usr/bin/python3.11
name = input("Enter your name : ")
city = input("enter your city : ")
print ("Hello My name is", name)
print ("I am from ", city)
When you run the program displays the prompt message, basically helping the
user what to enter.
Enter your name: Praveen Rao
enter your city: Bengaluru
Hello My name is Praveen Rao
I am from Bengaluru
Numeric Input
Let us write a Python code that accepts width and height of a rectangle from the
user and computes the area.
#! /usr/bin/python3.11
width = input("Enter width : ")
height = input("Enter height : ")
area = width*height
print ("Area of rectangle = ", area)
Run the program, and enter width and height.
Enter width: 20
Enter height: 30
Traceback (most recent call last):
File "C:\Python311\var1.py", line 5, in <module>
area = width*height
TypeError: can't multiply sequence by non-int of type 'str'
Why do you get a TypeError here? The reason is, Python always read the user
input as a string. Hence, width="20" and height="30" are the strings and
obviously you cannot perform multiplication of two strings.
To overcome this problem, we shall use int(), another built-in function from
Python's standard library. It converts a string object to an integer.
97
Python Basic
To accept an integer input from the user, read the input in a string, and type cast
it to integer with int() function −
w= input("Enter width : ")
width=int(w)
h= input("Enter height : ")
height=int(h)
You can combine the input and type cast statements in one −
#! /usr/bin/python3.11
width = int(input("Enter width : "))
height = int(input("Enter height : "))
area = width*height
print ("Area of rectangle = ", area)
Now you can input any integer value to the two variables in the program −
Enter width: 20
Enter height: 30
Area of rectangle = 600
Python's float() function converts a string into a float object. The following
program accepts the user input and parses it to a float variable − rate, and
computes the interest on an amount which is also input by the user.
#! /usr/bin/python3.11
amount = float(input("Enter Amount : "))
rate = float(input("Enter rate of interest : "))
interest = amount*rate/100
print ("Amount: ", amount, "Interest: ", interest)
The program ask user to enter amount and rate; and displays the result as
follows −
Enter Amount: 12500
Enter rate of interest: 6.5
Amount: 12500.0 Interest: 812.5
print() Function
Python's print() function is a built-in function. It is the most frequently used
function, that displays value of Python expression given in parenthesis, on
Python's console, or standard output (sys.stdout).
print ("Hello World ")
Any number of Python expressions can be there inside the parenthesis. They
must be separated by comma symbol. Each item in the list may be any Python
object, or a valid Python expression.
98
Python Basic
#! /usr/bin/python3.11
a = "Hello World"
b = 100
c = 25.50
d = 5+6j
print ("Message: a)
print (b, c, b-c)
print(pow(100, 0.5), pow(c,2))
The first call to print() displays a string literal and a string variable. The second
prints value of two variables and their subtraction. The pow() function
computes the square root of a number and square value of a variable.
Message Hello World
100 25.5 74.5
10.0 650.25
If there are multiple comma separated objects in the print() function's
parenthesis, the values are separated by a white space " ". To use any other
character as a separator, define a sep parameter for the print() function. This
parameter should follow the list of expressions to be printed.
In the following output of print() function, the variables are separated by
comma.
#! /usr/bin/python3.11
city="Hyderabad"
state="Telangana"
country="India"
print(city, state, country, sep=',')
The effect of sep=',' can be seen in the result −
Hyderabad,Telangana,India
The print() function issues a newline character ('\n') at the end, by default. As a
result, the output of the next print() statement appears in the next line of the
console.
city="Hyderabad"
state="Telangana"
print("City:", city)
print("State:", state)
Two lines are displayed as the output −
City: Hyderabad
State: Telangana
99
Python Basic
To make these two lines appear in the same line, define end parameter in the
first print() function and set it to a whitespace string " ".
city="Hyderabad"
state="Telangana"
country="India"
print("City:", city, end=" ")
print("State:", state)
Output of both the print() functions appear in continuation.
City: Hyderabad State: Telangana
Python - Numbers
Most of the times you work with numbers in whatever you do. Obviously, any
computer application deals with numbers. Hence, programming languages,
Python included, have built-in support to store and process numeric data.
In this chapter, we shall learn about properties of Python number types in detail.
Three number types, integers (int), floating point numbers (float) and complex
numbers, are built into the Python interpreter. Python also has a bult-in Boolean
data type called bool. It can be treated as a sub-type of int type, since its two
possible values True and False represent the integers 1 and 0 respectively.
Python − Integers
In Python, any number without the provision to store a fractional part is an
integer. (Note that if the fractional part in a number is 0, it doesn't mean that it is
an integer. For example a number 10.0 is not an integer, it is a float with 0
fractional part whose numeric value is 10.) An integer can be zero, positive or a
negative whole number. For example, 1234, 0, -55.
There are three ways to form an integer object. With literal representation, any
expression evaluating to an integer, and using int() function.
Literal is a notation used to represent a constant directly in the source code. For
example −
>>> a =10
However, look at the following assignment of the integer variable c.
a=10
b=20
c=a+b
print ("a:", a, "type:", type(a))
It will produce the following output −
a: 10 type: <class 'int'>
100
Python Basic
Here, c is indeed an integer variable, but the expression a+b is evaluated first,
and its value is indirectly assigned to c.
The third method of forming an integer object is with the return value of int()
function. It converts a floating point number or a string in an integer.
>>> a=int(10.5)
>>> b=int("100")
You can represent an integer as a binary, octal or Hexa-decimal number.
However, internally the object is stored as an integer.
Binary Numbers
A number consisting of only the binary digits (1 and 0) and prefixed with 0b is
a binary number. If you assign a binary number to a variable, it still is an int
variable.
A represent an integer in binary form, store it directly as a literal, or use int()
function, in which the base is set to 2
a=0b101
print ("a:",a, "type:",type(a))
b=int("0b101011",2)
print ("b:",b, "type:",type(b))
It will produce the following output −
a: 5 type: <class 'int'>
b: 43 type: <class 'int'>
There is also a bin() function in Python. It returns a binary string equivalent of
an integer.
a=43
b=bin(a)
print ("Integer:",a, "Binary equivalent:",b)
It will produce the following output −
Integer: 43 Binary equivalent: 0b101011
Octal Numbers
An octal number is made up of digits 0 to 7 only. In order to specify that the
integer uses octal notation, it needs to be prefixed by 0o (lowercase O) or 0O
(uppercase O). A literal representation of octal number is as follows −
a=0O107
print (a, type(a))
It will produce the following output −
71 <class 'int'>
101
Python Basic
Note that the object is internally stored as integer. Decimal equivalent of octal
number 107 is 71.
Since octal number system has 8 symbols (0 to 7), its base is 7. Hence, while
using int() function to covert an octal string to integer, you need to set the base
argument to 8.
a=int('20',8)
print (a, type(a))
It will produce the following output −
16 <class 'int'>
Decimal equivalent of octal 30 is 16.
In the following code, two int objects are obtained from octal notations and their
addition is performed.
a=0O56
print ("a:",a, "type:",type(a))
b=int("0O31",8)
print ("b:",b, "type:",type(b))
c=a+b
print ("addition:", c)
It will produce the following output −
a: 46 type: <class 'int'>
b: 25 type: <class 'int'>
addition: 71
To obtain the octal string for an integer, use oct() function.
a=oct(71)
print (a, type(a))
HEXA-DECIMAL NUMBERS
As the name suggests, there are 16 symbols in the Hexadecimal number system.
They are 0-9 and A to F. The first 10 digits are same as decimal digits. The
alphabets A, B, C, D, E and F are equivalents of 11, 12, 13, 14, 15, and 16
respectively. Upper or lower cases may be used for these letter symbols.
For the literal representation of an integer in Hexadecimal notation, prefix it by
0x or 0X.
a=0XA2
print (a, type(a))
It will produce the following output −
162 <class 'int'>
102
Python Basic
103
Python Basic
A floating point number has an integer part and a fractional part, separated by a
decimal point symbol (.). By default, the number is positive, prefix a dash (-)
symbol for a negative number.
A floating point number is an object of Python's float class. To store a float
object, you may use a literal notation, use the value of an arithmetic expression,
or use the return value of float() function.
Using literal is the most direct way. Just assign a number with fractional part to
a variable. Each of the following statements declares a float object.
>>> a=9.99
>>> b=0.999
>>> c=-9.99
>>> d=-0.999
In Python, there is no restriction on how many digits after the decimal point can
a floating point number have. However, to shorten the representation, the E or e
symbol is used. E stands for Ten raised to. For example, E4 is 10 raised to 4 (or
4th power of 10), e-3 is 10 raised to -3.
In scientific notation, number has a coefficient and exponent part. The
coefficient should be a float greater than or equal to 1 but less than 10. Hence,
1.23E+3, 9.9E-5, and 1E10 are the examples of floats with scientific notation.
>>> a=1E10
>>> a
10000000000.0
>>> b=9.90E-5
>>> b
9.9e-05
>>> 1.23E3
1230.0
The second approach of forming a float object is indirect, using the result of an
expression. Here, the quotient of two floats is assigned to a variable, which
refers to a float object.
a=10.33
b=2.66
c=a/b
print ("c:", c, "type", type(c))
It will produce the following output −
c: 3.8834586466165413 type <class 'float'>
104
Python Basic
105
Python Basic
One more such entity is Nan (stands for Not a Number). It represents any value
that is undefined or not representable.
>>> a=float('Nan')
>>> a
Nan
106
Python Basic
>>> a=1.01E-2+2.2e3j
>>> a
(0.0101+2200j)
>>> type(a)
<class 'complex'>
Note that the real part as well as the coefficient of imaginary part have to be
floats, and they may be expressed in standard decimal point notation or
scientific notation.
Python's complex() function helps in forming an object of complex type. The
function receives arguments for real and imaginary part, and returns the
complex number.
There are two versions of complex() function, with two arguments and with one
argument. Use of complex() with two arguments is straightforward. It uses first
argument as real part and second as coefficient of imaginary part.
a=complex(5.3,6)
b=complex(1.01E-2, 2.2E3)
print ("a:", a, "type:", type(a))
print ("b:", b, "type:", type(b))
It will produce the following output −
a: (5.3+6j) type: <class 'complex'>
b: (0.0101+2200j) type: <class 'complex'>
In the above example, we have used x and y as float parameters. They can even
be of complex data type.
a=complex(1+2j, 2-3j)
print (a, type(a))
It will produce the following output −
(4+4j) <class 'complex'>
Surprised by the above example? Put "x" as 1+2j and "y" as 2-3j. Try to
perform manual computation of "x+yj" and you'll come to know.
complex(1+2j, 2-3j)
=(1+2j)+(2-3j)*j
=1+2j +2j+3
=4+4j
If you use only one numeric argument for complex() function, it treats it as the
value of real part; and imaginary part is set to 0.
a=complex(5.3)
print ("a:", a, "type:", type(a))
107
Python Basic
108
Python Basic
a=int(True)
print ("bool to int:", a)
a=float(False)
print ("bool to float:", a)
a=complex(True)
print ("bool to complex:", a)
On running this code, you will get the following output −
bool to int: 1
bool to float: 0.0
109