0% found this document useful (0 votes)
0 views

Parts of Python Programming

Python is a high-level, general-purpose, interpreted, and object-oriented programming language created by Guido Van Rossum in 1991, known for its readability and versatility. It supports multiple programming paradigms, is beginner-friendly, and has a large standard library, making it popular in various fields such as web development, machine learning, and data science. Python is free and open-source, allowing for widespread use and distribution, and it operates through an interpreter that executes code line by line.

Uploaded by

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

Parts of Python Programming

Python is a high-level, general-purpose, interpreted, and object-oriented programming language created by Guido Van Rossum in 1991, known for its readability and versatility. It supports multiple programming paradigms, is beginner-friendly, and has a large standard library, making it popular in various fields such as web development, machine learning, and data science. Python is free and open-source, allowing for widespread use and distribution, and it operates through an interpreter that executes code line by line.

Uploaded by

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

PYTHON PROGRAMMING

UNIT – 1 – PARTS OF PYTHON PROGRAMMING LANGUAGE

Definition: Python is a high-level, general – purpose, interpreted, interactive and object-


oriented scripting language developed by Guido Van Rossum in 1991. Python is designed
to be highly readable. It uses English keywords frequently where as other languages use
punctuation, and it has fewer syntactical constructions than other languages.

Python is a general-purpose language which means it is versatile and can be used to


program many different types of functions. Because it is an interpreted language, it
precludes the need for compiling code before execution and because it is a high-level
programming language, Python is able to abstract details from code. In fact, Python
focuses so much attention on abstraction that its code can be understood by most novice
programmers. Python is one of the most highly ranked programming languages of today.

Python code tends to be short and when compared to compile languages like C and C++
that executes programs slower. Its user-friendliness makes it a popular language for
developers working with machine learning algorithms in low-code no-code (LCNC)
software applications.

Python is developed under an OSI-approved open source license, making it freely usable
and distributable, even for commercial use. Python's license is administered by the Python
Software Foundation. Open source software plays a very important role in our daily life.
Some of the most popular open source software is Android, Firefox, Linux, WordPress,
Python and others.

Python has a simple syntax and is known for having a large community that actively
contributes to a growing selection of software modules and libraries. Python’s initial
development was spearheaded by Guido van Rossum in the late 1980s. Today, Python is
managed by the Python Software Foundation.

 Python is Interpreted − Python is processed at runtime by the interpreter. We need


not compile our program before executing it. This is similar to PERL (Practical
Extraction and Report Language) and PHP (Hypertext Preprocessor).
 Python is Interactive – By using a Python prompt we can interact with the interpreter
directly to write programs.
 Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
 Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from
simple text processing to WWW browsers to games.
History of Python

The history of the Python programming language dates back to the late 1980s. Python was
developed in the late 1980s and its implementation was started in December 1989 by
Guido van Rossum, at the National Research Institute for Mathematics and Computer
Science in the Netherlands.

Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.
Python was developed as a successor to the ABC programming language.
Python labelled version was first published in February 1991 whereas, Python 1.0 was
launched in 1994. In 2000, Python 2.0 was released. Python 3.0 was released in 2008. It is
commonly known as “Py3K”.
Python is copyrighted. Like Perl, Python source code is now available under the GNU
General Public License (GPL).
Python is now maintained by a core development team at the institute, although Guido van
Rossum still holds a vital role in directing its progress.

Python Features: Python has become popular over the years. Python's popularity is due
to many factors. Some of the important features of Python Programming are:

1. Simple and Easy to learn:

 Python is a simple programming language, means that Python has few keywords,
simple structure and clearly defined syntax.
 When compared with other languages, we can write programs with very less
number of lines in Python. Hence more readability and simplicity in the Python
code.
 The indentation is used instead of flower brackets in Python which makes it very
easy to read Python code.

2. Interpreted Language:

 Interpreted in simple terms means running code line by line. An interpreted


language is a programming language that an interpreter executes to produce outputs.
 Python is called an interpreted language as it uses interpreter to execute the code
line by line.
 The developer is not required to compile the source code explicitly unlike C++ and
Java. Python internally compiles the source code and converts into byte code. The
bytecode is executed line by line by the Python virtual machine.
 Python is both compiled and interpreted. It is compiled language because Python
programs are compiled from source code to bytecode. It is interpreted language,
because Python programs are executed line by line by the Virtual Machine.
 Python will analyse each statement in the program and show and error message
present in that particular line at a time and then perform the desired action after
correcting it.

Note: Bytecode is a computer object code that an interpreter converts into binary
machine code so it can be read by a computer's hardware processor. The interpreter is
typically implemented as a virtual machine (VM) that translates the bytecode for the
target platform.

3. Dynamically Typed Language:

 Python is a dynamically typed language. Dynamically type means that unlike


other programming languages in Python we need not declare the data type of a
variable explicitly.
 The data type of the variable is decided at the runtime. From this one variable
can be used to store different types of data at different instances in the program.

4. Object Oriented Programming Language:

 Python supports various programming paradigms like structured programming,


functional programming, and object oriented programming. The most popular
fact is that the object oriented approach of Python allows its uses to implement
the concepts of encapsulation, polymorphism, etc, which is extremely important
to solve Real world problems using the object oriented approach.

5. Platform Independent or Portable:

 Platform independence refers to writing program once and can be run in any
platforms. It follows "Write Once Run Any Where" concept.
 Example: If we write a Python program on Windows operating system then we
can run the same code in Linux or any other operating system without any
changes. This is because the Python code first is converted to an intermediate
form known as "Bytecode" and then it is executed.
6. High Level Language:

 A high level language is a programming language that enables a programmer to


write programs that are more or less independent of a particular type of computer.
These languages are set to be high level since they are very easy to understand by
humans.
 Python is a high level programming language with very strong abstraction from the
low level construct of the system or Machine. While writing code, the developer
need not be concerned about the architecture, memory management or the
underlying machine type.

7. Free and Open Source:

 Python is free and open source software.


 Python is freely available. We can download it from the Python official website.
 Python is an open source which means that its source code is available to the public.
Anyone can download it, change it, use it and distribute it.

8. Large Standard Library:

 Python is extremely large with a diverse set of packages and modules. If the code
of some functionality is already present in these modules and packages, the
developers need not rewrite them from scratch saving both time and effort on the
developers end.

9. Extensible and Embeddable:

 Python is an embeddable language. We can write Python code into C or C++


language and also we can compile that code in C or C++ language.
 Python as an extensible language. It means that we can extend Python code in
various other languages also. This makes Python an extensible language, meaning
that it can be extended to other languages.

10. GUI Programming:

 Python offers various libraries for creating graphical user interface for any
application.
 The toolkits like wxPython or JPython allows for easy and fast development of
GUI.

11. Databases Support:

 Now a days almost every application need a database and Python Database API
(DB-API) that provides an interface to almost most of the major commercial
databases.
12. Procedure Oriented Programming:

 Python is one of the few programming language that supports both object oriented
programming as well as a procedure oriented programming and hence it is called as
multi paradigm programming language.
 Procedure oriented programming aims at creating various function or procedures to
solve specific task or set of task and aggregate them together in one piece of code.
A program can call the function as and when required. It purely depends on a
programmer whether to choose a procedure oriented programming or object
oriented programming style.

13. Supports Exception Handling:

 Python is one of the few languages that are capable of supporting exception
handling to a great extent which makes it a developer and programmer’s favourite
language.

14. Robust:

 Robust means strong. Python's ability to work well with exceptions and exception
handling as well as its ease of use and comprehension has reduced the error rate in
the code. This makes the language very reliable and robust language to work with.

Interpreter / Shell: Python is an interpreter language. It means it executes the code


line by line. Python provides a Python Shell, which is used to execute a single Python
command and display the result.
Python Interpreter
 CPython. It is the default and maximum used for the execution of the Python
programming language.
 Jython. Formerly referred to as JPython, Jython is used in implementation of Python
that runs on the Java platform.
 PyPy, PythonNet, Stackless Python.

Working of Python Interpreter:


Python doesn’t convert its code into bytecode. So within Python, compilation happens, but
it’s just not in a machine language, it is into bytecode (.pyc or .pyo) and this bytecode
can’t be understood by the CPU. So we need an interpreter called the Python virtual
machine to execute the bytecodes.

The Python source code goes through the following to generate an executable code

Step 1: The Python compiler reads a Python source code or instruction in the code editor.
In this first stage, the execution of the code starts.

Step 2: After writing Python code it is then saved as a .py file in our system. In this, there
are instructions written by a Python script for the system.

Step 3: In this the compilation stage comes in which source code is converted into a byte
code. Python compiler also checks the syntax error in this step and generates a .pyc file.

Step 4: Bytecode that is .pyc file is then sent to the Python Virtual Machine(PVM) which
is the Python interpreter. PVM converts the Python bytecode into machine-executable
code and in this interpreter reads and executes the given file line by line. If an error occurs
during this interpretation then the conversion is halted with an error message.

Step 5: Within the PVM the bytecode is converted into machine code that is the binary
language consisting of 0’s and 1’s. This binary language is only understandable by the
CPU of the system as it is highly optimized for the machine code.

Step 6: In the last step, the final execution occurs where the CPU executes the machine
code and the final desired output will come as according to the program.

Interpreter in Python with example:


When we write a Python code in a text file with a name like hello.py
How does that code Run? There is program installed on computer named "Python3" or
"Python", and its job is looking at and running the Python code. This type of program is
called an "interpreter".
The Python interpreter is a bytecode interpreter: its input is instruction sets called
bytecode. When we write Python, the lexer (a component of the Python interpreter), parser
(another component of the Python interpreter), and compiler generate code objects for the
interpreter to operate on.
The Python Shell is the interpreter that executes Python programs, other pieces of Python
code, or simple commands.

Differences between Compiler and Interpreter:


In the system both the compiler and interpreter are the same. They convert high-level
code to machine code. The interpreter converts source code into the machine when the
program runs in a system while a compiler converts the source code into machine code
before the program runs in our system.

Compiler Interpreter
The compiler is faster, as conversion The interpreter runs slower as the execution
occurs before the program executes. occurs simultaneously.
Errors are detected during the compilation Errors are identified and reported during the
phase and displayed before the execution given actual runtime.
of a program.
Compile code needs to be recompiled to Interpreted code is more portable as it can
run on different machines. run on any machine with the appropriate
interpreter.
It requires more memory to translate the It requires less memory than compiled ones.
whole source code at once.
Debugging is more complex due to batch Debugging is easier due to the line-by-line
processing of the code. execution of a code.

Applications of Python:
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.
Some of the applications of Python are:
 Web Development
 Game Development
 Machine Learning and Artificial Intelligence
 Data Science and Data Visualization
 Desktop GUI
 Software Development
 Operating Systems
 Network Programming
 Embedded Software
 Web Scraping Applications
 Business Applications
 Language Development
 Audio and Video Applications
 Robotics
 Console - based application
Differences between C and Python

C Python
C is a general-purpose, procedural Python is an interpreted, high-level,
computer programming language. general-purpose programming language.
Compiled programs execute faster as Interpreted programs execute slower as
compared to interpreted programs. compared to compiled programs.
Program syntax is harder than Python. It is easier to write a code in Python as the
number of lines is less comparatively.
In C, the type of a variable must be There is no need to declare the type of
declared when it is created, and only variable. A given variable can be stuck on
values of that type must be assigned to it. values of different types at different times
during the program execution
In C, error debugging is difficult as it is a Error debugging is simple. This means it
compiler dependent language. This means takes only one in instruction at a time and
that it takes the entire source code, compiles and executes simultaneously.
compiles it and then shows all the errors. Errors are shown instantly and the
execution is stopped, at that instruction.
C does not support function renaming Supports function renaming mechanism i.e,
mechanism. This means the same function the same function can be used by two
cannot be used by two different names. different names.
The syntax of a C program is harder than Syntax of Python programs is easy to learn,
Python. write and read.
C is generally used for hardware related Python is a General-Purpose programming
applications. language.
Platform Dependent Platform Independent

Differences between Java and Python


Java Python
Java is an object oriented programming Python is both Procedure Oriented and
language. Object Oriented Programming Language.
Java is a compiled language. Python is an interpreted language.
Statically typed language. Dynamically typed language.
Java has a complex learning curve. Python is easy to learn and use.
Java uses flower brackets to highlight the Python does not use any flower brackets but
start / end of any function or class. a proper indentation must be followed.
More lines of code. Fewer lines of code.
Java is faster in speed compared to Python. Python is slower since it uses interpreter
and also determines the datatype at run
time.
Syntax is complex. Syntax is easy to remember.

Installing Python
Installing and using Python on Windows Operating System is very simple. The installation
procedure involves the following steps:
Step 1 - Select Version of Python to Install
 Python has various versions available with differences between the syntax and
working of different versions of the language. We need to choose the version which
we want to use or need. There are different versions of Python 2 and Python 3
available.
Step 2 − Download Python Executable Installer
 On the web browser, in the official site of Python (www.Python.org), move to the
Download for Windows section.
 All the available versions of Python will be listed. Select the version required by
you and click on Download. Let suppose, we chose the Python 3.9.1 version.
 On clicking download, various available executable installers shall be visible with
different operating system specifications. Choose the installer which suits your
system operating system and download the instlaller. Let suppose, we select the
Windows installer(64 bits).
Step 3 − Run Executable Installer
 We downloaded the Python 3.9.1 Windows 64 bit installer.
 Run the installer. Make sure to select both the checkboxes at the bottom and then
click Install New.
 The installation process will take few minutes to complete and once the
installation is successful, the following screen is displayed.
Step 4 − Verify Python is installed on Windows
To ensure if Python is successfully installed on your system.
Follow the given steps:
 Open the command prompt.
 Type ‘Python’ and press enter.
 The version of the Python which you have installed will be displayed if the
Python is successfully installed on your windows.
Step 5 − Verify Pip was installed
 Pip (Preferred Installer Program – used to install packages) is a powerful
package management system for Python software packages. Thus, make sure
that you have it installed.
 To verify if pip was installed, follow the given steps −
 Open the command prompt.
 Enter pip –V to check if pip was installed.
We have successfully installed Python and pip on our Windows system.

In the Python programming language, there are two ways in which we can run our
code:
1. Interactive mode
2. Script mode
1. Interactive Mode:
 In the interactive mode as we enter a command and press enter, the very next step
we get the output.
 The output of the code in the interactive mode is influenced by the last command we
give.
 Interactive mode is very convenient for writing very short lines of code.
 It is not user friendly way to write long code.
In Python it is also known as REPL which stands for Read Evaluate Print Loop.
 The read function reads the input from the user and stores it in memory.
 Eval function evaluates the input to get the desired output.
 Print function outputs the evaluated result.
 The loop function executes the loop during the execution of the entire program and
terminates when our program ends.
 This mode is very suitable for beginners in programming as it helps them evaluate
their code line by line and understand the execution of code well.
 Working in the interactive mode is convenient for testing a single line of code for
instant execution. but in the interactive mode, we cannot save the statements for
future use and we have to retype the statements to run them again.
 To close the interactive session we can type quit() or exit().
Interactive mode using Command Prompt
In order to run our program in the interactive mode, we can use command prompt in
windows, terminal in Linux, and macOS.
Example:
To run Python in command prompt type “Python”. Then simply type the Python statement
on >>> prompt. As we type and press enter we can see the output in the very next line.

2. Script Mode: In the script mode, a Python program can be written in a file. This
file can then be saved and executed using the command prompt. We can view the
code at any time by opening the file and editing becomes quite easy as we can open
and view the entire code as many times as we want. Script mode is very suitable for
writing long pieces of code. It is much preferred over interactive mode by experts in
the program. The file made in the script mode is by default saved in the Python
installation folder and the extension to save a Python file is “.py”.
Execution of Python code in script mode
In order to run a code in script mode follow the following steps.
Step 1: Make a file using a text editor.
Step 2: After writing the code save the file using “.py” extension.
Step 3: Now open the command prompt and command directory to the one where your
file is stored.
Step 4: Type Python “filename.py” and press enter.
Step 5: You will see the output on your command prompt.
Executing a Python Program Script
We have to execute a Python program script in order to get the output of the program, and
we have two ways for it.
1. Executing using command prompt terminal
Step 1: Open the command prompt and go to the directory where the Python script
file is saved.
Step2: Type Python followed by the file name. When we press enter key, Python
will start executing the script file in the command prompt terminal. We can see the
output as shown below:

2. Executing Python Script using Python IDLE


Python IDLE: It stands for Integrated Development and Learning Environment.
It allows programmers to easily write Python code. Just like Python Shell, IDLE can
be used to execute a single statement and create, modify, and execute Python
scripts.
IDLE provides a fully featured text editor to create Python scripts that include
features like syntax highlighting, auto completion, and smart indent. It also has a
debugger with stepping and breakpoints features. This makes debugging easier.

Python Tokens:
A token is the smallest individual unit in a Python program. The different types of
tokens in Python are:

1. IDENTIFIERS: An identifier is a name given to a variable, function, class or


module. Identifiers may be one or more characters in the following format:
 Identifiers can be a combination of letters in lowercase (a to z) or uppercase
(A to Z) or digits (0 to 9) or an underscore (_).
 Names like myCountry, other_1 and good_morning, all are valid examples.
 A Python identifier can begin with an alphabet (A – Z and a – z and _).
 An identifier cannot start with a digit but is allowed everywhere else. 1plus is
invalid, but plus1 is perfectly fine.
 Keywords cannot be used as identifiers.
 One cannot use spaces and special symbols like !, @, #, $, % etc. as identifiers.
 Identifier can be of any length.

2. KEYWORDS: Keywords are a list of reserved words that have predefined


meaning. Keywords are special vocabulary and cannot be used by programmers as
identifiers for variables, functions, constants or with any identifier name.
Attempting to use a keyword as an identifier name will cause an error. The
following TABLE shows the Python keywords.
Keyword Description

True This keyword represents the Boolean Value ‘true.’

False This keyword represents the Boolean Value ‘false.’

None This keyword represents the Null Value

And This is a logical operator

As This keyword used for creating an alias


The assert keyword is used to insert debugging assertions in the
Assert
program.
Async This keyword is always used in the coroutine function body.

Await This keyword is used for asynchronous processing.

Break This keyword is used to break the loop.

Class This keyword is used to define a class.

Continue This keyword is used to take the control back to the loop.

Def This keyword is used to define a function.


This keyword is used to delete objects like variables, lists, or any other
Del
kind of object.
This keyword is used for a conditional statement along with an if
Elif
statement.
Else This keyword is also used as a conditional statement, the same as above.

Except This keyword is used for exceptional handling in Python.


This keyword is used for exceptional handling, but finally, the block will
Finally
always get executed.
This keyword is used as a looping statement used to iterate over the
For
elements of a sequence.
From This keyword is used to import a function in Python.
Global This keyword is used to declare global variables.

If This keyword is used to declare a condition in Python.

Import This keyword is used for importing the module in Python.


This keyword is used to check specific values are present in an iterable
In
object.
Is This keyword is used to test object identity

Lambda This keyword is used to make anonymous functions.


This keyword is used to access the variables defined outside of the scope
Nonlocal
in the block.
Not This keyword is used to negates a Boolean value.
This keyword is used for a conditional statement where at least one
Or
condition must be fulfilled.
Pass This keyword is used to tell the program or a function to do nothing.
Raise This keyword is used to create a user define exception.
Return This keyword is used to return a value at the time function is exited
Try This keyword is used to specifies the exception handlers.
This keyword is used to run a block of statements till the expression is
While
fulfilled
With This keyword is used to open a file.
Yield This keyword is a replacement for a return keyword.

Statements and Expressions: A statement is an instruction that the Python interpreter


can execute. Python program consists of a sequence of statements. Statements are
everything that can make up a line (or several lines) of Python code.
For example, z = 1 is an assignment statement.
Expression is an arrangement of values and operators which are evaluated to make a new
value. Expressions are statements as well. A value is the representation of some entity like
a letter or a number that can be manipulated by a program.
A single value >>> 20 or a single variable >>> z
or a combination of variable, operator and value >>> z + 20 are all
examples of expressions.
An expression, when used in interactive mode is evaluated by the interpreter and result is
displayed instantly. For example,
>>> 8 + 2
10
Note: But the same expression when used in Python program does not show any output
altogether. You need to explicitly print the result.
Difference between Expressions and Statements in Python:
Expression Statement

An expression evaluates to a A statement executes something


value

The evaluation of a statement The execution of a statement changes state


does not changes state

Evaluation of an expression Execution of a statement may or may not


always Produces or returns a produces or displays a result value, it only does
result value. whatever the statement says.

Every expression can’t be a Every statement can be an expression.


statement.

Example: >>> a + 16 Example: >>> x = 3


>>> 20 >>> print(x)

Output: 3

Note:
 The execution of a statement changes state
 Execution of a statement may or may not produces or displays a result value, it only
does whatever the statement says.

VARIABLES: Variable is a name given to hold any type of data which the program can
use to assign and modify during the course of execution. In Python, there is no need to
declare a variable explicitly by specifying whether the variable is an integer or a float or
any other type. To define a new variable in Python, we simply assign a value to a name. If
a need for variable arises you need to think of a variable name based on the rules
mentioned in the following subsection and use it in the program.
Legal Variable Names:
Rules for creating legal variable names in Python.
 Variable names can consist of any number of letters, underscores and digits.
 Variable should not start with a number.
 Python Keywords are not allowed as variable names.
 Variable names are case-sensitive. For example, computer and Computer are
different variables.
The guidelines while naming a variable are, as having a consistent naming convention
helps in avoiding confusion and can reduce programming errors.
• Python variables use lowercase letters with words separated by underscores as
necessary to improve readability, like this whats_up, how_are_you. Although this is not
strictly enforced, it is considered a best practice to adhere to this convention.
• Avoid naming a variable where the first character is an underscore. While this is legal in
Python, it can limit the interoperability of your code with applications built by using other
programming languages.
• Ensure variable names are descriptive and clear enough. This allows other programmers
to have an idea about what the variable is representing.
Assigning Values to Variables: The general format for assigning values to variables
is as follows:
variable_name = expression
The equal sign (=) also known as simple assignment operator is used to assign values to
variables. In the general format, the operand to the left of the = operator is the name of the
variable and the operand to the right of the = operator is the expression which can be a
value or any code snippet that results in a value. That value is stored in the variable on
the execution of the assignment statement. Assignment operator should not be confused
with the = used in algebra to denote equality. For example, enter the code shown below in
interactive mode and observe the results.
1. >>> number =100
2. >>> miles =1000.0
3. >>> name ="Python"
4. >>> number
100
5. >>> miles
1000.0
6. >>> name
'Python'
In ➀ integer type value is assigned to a variable number, in ➁ float type value has been
assigned to variable miles and in ➂ string type value is assigned to variable name. ➃, ➄
and ➅ prints the value assigned to these variables.
In Python, not only the value of a variable may change during program execution but also
the type of data that is assigned. You can assign an integer value to a variable, use it as an
integer for a while and then assign a string to the variable. A new assignment overrides
any previous assignments. For example,
1. >>> century = 100
2. >>> century
100
3. >>> century = "hundred"
4. >>> century
'hundred'
In ➀ an integer value is assigned to century variable and then in ➂ you are assigning a
string value to century variable. Different values are printed in each case as seen in ➁ and
➃. Python allows you to assign a single value to several variables simultaneously. For
example,
1. >>> a = b = c =1
2. >>> a
1
3. >>> b
1
4. >>> c
1
An integer value is assigned to variables a, b and c simultaneously ➀. Values for each of
these variables are displayed as shown in ➁, ➂ and ➃.
3. Operators: Operators are symbols, such as +, –, =, >, and <, that perform certain
mathematical or logical operation to manipulate data values and produce a result
based on some rules. An operator manipulates the data values called operands.
Consider the expression,
>>> 4 + 6
where 4 and 6 are operands and + is the operator.
Python language supports a wide range of operators. They are
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
1. Arithmetic Operators: Arithmetic operators are used to execute arithmetic operations
such as addition, subtraction, division, multiplication etc. The following table shows all
the arithmetic operators.
For example,
1. >>> 10+35
45
2. >>> −10+35
25
3. >>> 4*2
8
4. >>> 4**2
16
1. + Addition operator Adds two operands, producing their sum.
Eg: p + q = 5
2. − Subtraction operator Subtracts the two operands, producing their difference.
Eg: p – q = −1
3.* Multiplication operator Produces the product of the operands.
Eg: p * q = 6
4. / Division operator Produces the quotient of its operands where the
left operand is the dividend and the right operand is the divisor.
Eg: q / p = 1.5
5. % Modulus operator Divides left hand operand by right hand operand
and returns a remainder.
Eg: q % p = 1
6. ** Exponent operator Performs exponential (power) calculation on
operators.
Eg: p**q = 8
7. // Floor division operator Returns the integral part of the quotient.
Eg: 9//2 = 4 and 9.0//2.0 = 4.0
Note: The value of p is 2 and q is 3.
For example,
1. >>> 10+35
45
2. >>> −10+35
25
3. >>> 4*2
8
4. >>> 4**2
16
5. >>> 45/10
4.5
6. >>> 45//10.0
4.0
7. >>> 2025%10
5
8. >>> 2025//10
202
Above code illustrates various arithmetic operations ➀–➇.
2.Assignment Operators: Assignment operators are used for assigning the values
generated after evaluating the right operand to the left operand. Assignment operation
always works from right to left.
Assignment operators are either simple assignment operator or compound assignment
operators.
Simple assignment is done with the equal sign (=) and simply assigns the value of its
right operand to the variable on the left. For example,
1. >>> x = 5
2. >>> x = x + 1
3. >>> x
6
In ➀ you assign an integer value of 5 to variable x. In ➁ an integer value of 1 is added to
the variable x on the right side and the value 6 after the evaluation is assigned to the
variable x. The latest value stored in variable x is displayed in ➂Compound assignment
operators support shorthand notation for avoiding the repetition of the left-side variable on
the right side. Compound assignment operators combine assignment operator with another
operator with = being placed at the end of the original operator.
For example, the statement
>>> x = x + 1
can be written in a compactly form as shown below.
>>> x += 1
If you try to update a variable which doesn’t contain any value, you get an error.
1. >>> z = z + 1
NameError: name 'z' is not defined
Trying to update variable z which doesn’t contain any value results in an error because
Python evaluates the right side before it assigns a value to z ➀.
1. >>> z = 0
2. >>> x = z + 1
Before you can update a variable ➁, you have to assign a value to it ➀.
List of Assignment Operators
1. = Assignment Assigns values from right side operands to left side operand.
z = p + q assigns value of p + q to z
2. += Addition Assignment Adds the value of right operand to the left operand and
assigns the result to left operand.
z += p is equivalent to z = z + p
3. −= Subtraction Assignment Subtracts the value of right operand from the left operand
and assigns the result to left operand.
z −= p is equivalent to z = z – p
4. *= Multiplication Assignment Multiplies the value of right operand with the left
operand and assigns the result to left operand.
z *= p is equivalent to z = z * p
5. /= Division Assignment Divides the value of right operand with the left operand and
assigns the result to left operand.
z /= p is equivalent to z = z / p
6.**= Exponentiation Assignment Evaluates to the result of raising the first operand to
the power of the second operand.
z**= p is equivalent to z = z ** p
7. //= Floor Division Assignment Produces the integral part of the quotient of its
operands where the left operand is the dividend and the right operand is the divisor.
z //= p is equivalent to z = z // p
8. %= Remainder Assignment Computes the remainder after division and assigns the
value to the left operand.
z %= p is equivalent to z = z % p
For example,
1. >>> p = 10
2. >>> q = 12
3. >>> q += p
4. >>> q
22
5. >>> q *= p
6. >>> q
220
7. >>> q /= p
8. >>> q
22.0
9. >>> q %= p
10. >>> q
2.0
11. >>> q **= p
12. >>> q
1024.0
13. >>> q //= p
14. >>> q
102.0
Above code illustrates various assignment operations ➀–14 .
3.Comparison Operators: When the values of two operands are to be compared then
comparison operators are used. The output of these comparison operators is always a
Boolean value, either True or False. The operands can be Numbers or Strings or Boolean
values. Strings are compared letter by letter using their ASCII values, thus, “P” is less than
“Q”, and “Aston” is greater than “Asher”.
List of Comparison Operators
1.== Equal to If the values of two operands are equal, then the condition becomes True.
Eg: (p == q) is not True.
2.!= Not Equal to If values of two operands are not equal, then the condition becomes
True.
Eg: (p != q) is True
3.> Greater than If the value of left operand is greater than the value of right operand, then
condition becomes True.
Eg: (p > q) is not True.
4. < Lesser than If the value of left operand is less than the value of right operand, then
condition becomes True.
Eg: (p < q) is True.
5. >= Greater than or equal to If the value of left operand is greater than or equal to the
value of right operand, then condition becomes True.
Eg: (p >= q) is not True.
6. <= Lesser than or equal to If the value of left operand is less than or equal to the value
of right operand, then condition becomes True.
Eg: (p <= q) is True.
Note: The value of p is 10 and q is 20.
For example,
1. >>>10 == 12
False
2. >>>10 != 12
True
3. >>>10 < 12
True
4. >>>10 > 12
False
5. >>>10 <= 12
True
6. >>>10 >= 12
False
7. >>> "P" < "Q"
True
8. >>> "Aston" > "Asher"
True
9. >>> True == True
True
Above code illustrates various comparison operations ➀–➈.

4. Logical Operators: The logical operators are used for comparing or negating the
logical values of their operands and to return the resulting logical value. The values of the
operands on which the logical operators operate evaluate to either True or False. The result
of the logical operator is always a Boolean value, True or False.
List of Logical Operators
1. and Logical AND Performs AND operation and the result is True when both operands
are True
Eg: p and q results in False
2. or Logical OR Performs OR operation and the result is True when any one of both
operand is True
Eg: p or q results in True
3. not Logical NOT Reverses the operand state
Eg: not p results in False
Note: The Boolean value of p is True and q is False.
Boolean Logic Truth Table
P Q P and Q P or Q Not P
True True True True False
True False False True
False True False True True
False False False False

For example,
1. >>> True and False
False
2. >>> True or False
True
3. >>> not(True) and False
False
4. >>> not(True and False)
True
5. >>> (10 < 0) and (10 > 2)
False
6. >>> (10 < 0) or (10 > 2)
True
7. >>> not(10 < 0) or (10 > 2)
True
8. >>> not(10 < 0 or 10 > 2)
False
Above code illustrates various comparison operations ➀–➇.
For example,
1. >>> 1 > 2 and 9 > 6
False
2. >>> 3 > 2 or 8 < 4
True
In ➀ the expression 1 > 2 is evaluated to False. Since and operator is used in the statement
the expression is evaluated to False and the remaining expression 9 > 6 is not evaluated.
In ➁ the expression 3 > 2 is evaluated to True. As or operator is used in the statement the
expression is evaluated to True while the remaining expression 8 < 4 is ignored.
5. Bitwise Operators: Bitwise operators treat their operands as a sequence of bits (zeroes
and ones) and perform bit by bit operation.
For example, the decimal number ten has a binary representation of 1010. Bitwise
operators perform their operations on such binary representations, but they return standard
Python numerical values. TABLE below shows all the bitwise operators.
The Bitwise Truth table is shown below

The figure below shows examples for bitwise logical operations. The value of operand a is
60 and value of operand b is 13
Examples of bitwise logical operators.

The figure below shows how the expression 60 << 2 would be evaluated in a byte.

Example of bitwise left shift of two bits


Due to this operation,
• Each of the bits in the operand (60) is shifted two places to the left.
• The two bit positions emptied on the right end are filled with 0s.
• The resulting value is 240.
For example,
1. >>> p =60
2. >>> p << 2
240
3. >>> p = 60
4. >>> p >> 2
15
5. >>> q = 13
6. >>> p & q
12
7. >>> p | q
61
8. >>> ~p
–61
9. >>> p << 2
240
10. >>> p >> 2
15
Above code illustrates various Bitwise operations ➀–10
Precedence and Associativity: Operator precedence determines the way in which
operators are parsed with respect to each other. Operators with higher precedence become
the operands of operators with lower precedence. Associativity determines the way in
which operators of the same precedence are parsed. Almost all the operators have left-to-
right associativity. Operator precedence is listed in the table below starting with the
highest precedence to lowest precedence.
Consider the following code,
1. >>> 2 + 3 * 6
20
2. >>> (2 + 3) * 6
30
3. >>> 6 * 4 / 2
12.0
Expressions with higher-precedence operators are evaluated first. In ➀ multiplication * is
having precedence over addition. So, 3 * 6 gets evaluated first and the result is added to
2.This behaviour can be overridden using parentheses as shown in ➁. Parentheses have
the highest precedence and the expression inside the parentheses gets evaluated first,
which in our case is 2 + 3 and the result is multiplied with 6. In ➂ both multiplication and
division have the same precedence hence starting from left to right, the multiplication
operator is evaluated first and the result is divided by 2.
Data Types:

Data types specify the type of data like numbers and characters to be stored and
manipulated within a program. Basic data types of Python are:
• Numbers
• Boolean
• Strings
• None
1. Numbers: Integers, floating point numbers and complex numbers fall under Python
numbers category. They are defined as int, float and complex class in Python. Integers can
be of any length; it is only limited by the memory available. A floating point number is
accurate up to 15 decimal places. Integer and floating points are separated by decimal
points. 1 is an integer, 1.0 is floating point number. Complex numbers are written in the
form, x + yj, where x is the real part and y is the imaginary part.
2. Boolean: Booleans may not seem very useful at first, but they are essential when you
start using conditional statements. In fact, since a condition is really just a yes-or-no
question, the answer to that question is a Boolean value, either True or False. The Boolean
values, True and False are treated as reserved words.
3. Strings: A string consists of a sequence of one or more characters, which can include
letters, numbers, and other types of characters. A string can also contain spaces. You can
use single quotes or double quotes to represent strings and it is also called a string literal.
Multiline strings can be denoted using triple quotes, ''' or """. These are fixed values, not
variables that you literally provide in your script.
For example : -
1. >>> s = 'This is single quote string'
2. >>> s = "This is double quote string"
3. >>> s = '''This is
Multiline
string'''
4. >>> s = "a"
In ➀ a string is defined using single quotes, in ➁ a string is defined using double quotes
and a multiline string is defined in ➂, a single character is also treated as string ➃.
4. None: None is another special data type in Python. None is frequently used to represent
the absence of a value. For example:-
1. >>> money = None
None value is assigned to variable money ➀.
Indentation: In Python, Programs get structured through indentation. Usually, we expect
indentation from any program code, but in Python it is a requirement and not a matter of
style. This principle makes the code look cleaner and easier to understand and read. Any
statements written under another statement with the same indentation is interpreted to
belong to the same code block.
Figure representing Code blocks and Indentation in Python
If there is a next statement with less indentation to the left, then it just means the end of the
previous code block. In other words, if a code block has to be deeply nested, then the
nested statements need to be indented further to the right. In the above diagram, Block 2
and Block 3 are nested under Block 1. Usually, four whitespaces are used for indentation
and are preferred over tabs. Incorrect indentation will result in IndentationError.
Comments: Comments are an important part of any program. A comment is a text that
describes what the program or a particular part of the program is trying to do and is
ignored by the Python interpreter. Comments are used to help you and other programmers
understand, maintain, and debug the program. Python uses two types of comments: single-
line comment and multiline comments.
1. Single Line Comment: In Python, use the hash (#) symbol to start writing a comment.
Hash (#) symbol makes all text following it on the same line into a comment. For example,
#This is single line Python comment
2. Multiline Comments: If the comment extends multiple lines, then one way of
commenting those lines is to use hash (#) symbol at the beginning of each line. For
example,
#This is
#multiline comments
#in Python
Another way of doing this is to use triple quotes, either ''' or """. These triple quotes are
generally used for multiline strings. However, they can be used as a multiline comment as
well.
For example,
'''This is
multiline comment
in Python using triple quotes'''
Reading Input: In Python, input() function is used to gather data from the user. The
syntax for input function is,
variable_name = input([prompt])
prompt is a string written inside the parenthesis that is printed on the screen. The prompt
statement gives an indication to the user of the value that needs to be entered through the
keyboard. When the user presses Enter key, the program resumes and input returns what
the user typed as a string. Even when the user inputs a number, it is treated as a string
which should be casted or converted to number explicitly using appropriate type casting
function.
1. >>> person = input("What is your name?")
2. What is your name? Carrey
3. >>> person
'Carrey'
➀ the input() function prints the prompt statement on the screen (in this case "What is
your name?") indicating the user that keyboard input is expected at that point and then it
waits for a line to be typed in. User types in his response in ➁. The input() function reads
the line from the user and converts the line into a string. As can be seen in ➂, the line
typed by the user is assigned to the person variable.

Print Output: The print() function allows a program to display text onto the console. The
print function will print everything as strings and anything that is not already a string is
automatically converted to its string representation. For example,
1. >>> print("Hello World!!")
Hello World!!
➀ prints the string Hello World!! onto the console. Notice that the string Hello World is
enclosed within double quotes inside the print() function.
Even though there are different ways to print values in Python, we discuss two major
string formats which are used inside the print() function to display the contents onto the
console as they are less error prone and results in cleaner code. They are
1. str.format()
2. f-strings
1. str.format( ): Use str.format() method if you need to insert the value of a variable,
expression or an object into another string and display it to the user as a single string. The
format() method returns a new string with inserted values. The format() method works for
all releases of Python 3.x. The syntax for format() method is,
str.format(p0, p1, ..., k0=v0, k1=v1, ...)
where p0, p1,... are called as positional arguments and, k0, k1,... are keyword arguments
with their assigned values of v0, v1,... respectively.
Positional arguments are a list of arguments that can be accessed with an index of
argument inside curly braces like {index}. Index value starts from zero.
Keyword arguments are a list of arguments of type keyword = value, that can be accessed
with the name of the argument inside curly braces like {keyword}.
Here, str is a mixture of text and curly braces of indexed or keyword types. The indexed or
keyword curly braces are replaced by their corresponding argument values and is
displayed as a single string to the user.

Program 1: Program to Demonstrate input() and print() Functions


country = input("Which country do you live in?")
print("I live in {0}".format(country))

Output
Which country do you live in? India
I live in India
Program 2: Program to Demonstrate the Positional Change of Indexes of Arguments
a = 10
b = 20
print("The values of a is {0} and b is {1}".format(a, b))
print("The values of b is {1} and a is {0}".format(a, b))
Output
The values of a is 10 and b is 20
The values of b is 20 and a is 10

2. f-strings: Formatted strings or f-strings were introduced in Python 3.6. A f-string is a


string literal that is prefixed with “ f ”. These strings may contain replacement fields,
which are expressions enclosed within curly braces {}. The expressions are replaced with
their values. In the real world, it means that you need to specify the name of the variable
inside the curly braces to display its value. An f at the beginning of the string tells Python
to allow any currently valid variable names within the string.

Program 3: Code to Demonstrate the Use of f-strings with print() Function


country = input("Which country do you live in?")
print(f"I live in {country}")
Output
Which country do you live in? India
I live in India
Program 4: Given the Radius, Write Python Program to Find the Area and
Circumference of a Circle
radius = float(input(“Enter the radius of a circle”))
area = 3.1415 * radius * radius
circum = 2 * 3.1415 * radius
print(“Area = ”, area )
print (“Circumference =”, circum)
Output
Enter the radius of a circle 5
Area = 78.53750000000001 and Circumference = 31.415000000000003
Program 5: Write Python Program to Convert the Given Number of Days to a
Measure of Time Given in Years, Weeks and Days. For Example, 375 Days Is Equal
to 1 Year, 1 Week and 3 Days (Ignore Leap Year).
number_of_days = int(input("Enter number of days"))
number_of_years = int(number_of_days /365)
number_of_weeks = int(number_of_days % 365 / 7)
remaining_number_of_days = int(number_of_days % 365 % 7)
print(f"Years = {number_of_years}, Weeks = {number_of_weeks}, Days =
{remaining_number_of_days}")
Output
Enter number of days 375
Years = 1, Weeks = 1, Days = 3
Type Conversions: We can explicitly cast, or convert, a variable from one type to
another.
1. The int() Function : To explicitly convert a float number or a string to an integer, cast
the number using int() function.
Program 6: Program to Demonstrate int() Casting Function
float_to_int = int(3.5)
string_to_int = int("1") #number treated as string
print(f"After Float to Integer Casting the result is {float_to_int}")
print(f"After String to Integer Casting the result is {string_to_int}")
Output
After Float to Integer Casting the result is 3
After String to Integer Casting the result is 1
1. >>>numerical_value = input("Enter a number")
Enter a number 9
2. >>> numerical_value
'9'
3. >>> numerical_value = int(input("Enter a number"))
Enter a number 9
4. >>> numerical_value
9
2. The float() Function: The float() function returns a floating point number constructed
from a number or string.
Program 7: Program to Demonstrate float() Casting Function You can explicitly cast,
or convert, a variable from one type to another.
int_to_float = float(4)
string_to_float = float("1") #number treated as string
print(f"After Integer to Float Casting the result is {int_to_float}")
print(f"After String to Float Casting the result is {string_to_float}")
Output
After Integer to Float Casting the result is 4.0
After String to Float Casting the result is 1.0
3. The str() Function: The str() function returns a string which is fairly human readable.
Program 8: Program to Demonstrate str() Casting Function
int_to_string = str(8)
float_to_string = str(3.5)
print(f"After Integer to String Casting the result is {int_to_string}")
print(f"After Float to String Casting the result is {float_to_string}")
Output
After Integer to String Casting the result is 8
After Float to String Casting the result is 3.5
4. The chr() Function: Convert an integer to a string of one character whose ASCII code
is same as the integer using chr() function. The integer value should be in the range of 0–
255.
Program 9: Program to Demonstrate chr() Casting Function
ascii_to_char = chr(100)
print(f" Equivalent Character for ASCII value of 100 is {ascii_to_char}")
Output
Equivalent Character for ASCII value of 100 is d
5. The complex() Function: Use complex() function to print a complex number with the
value real + imag*j or convert a string or number to a complex number. If the first
argument for the function is a string, it will be interpreted as a complex number and the
function must be called without a second parameter. The second parameter can never be a
string. Each argument may be any numeric type (including complex). If imag is omitted,it
defaults to zero and the function serves as a numeric conversion function like int(),long()
and float().If both arguments are omitted, the complex() function returns 0j.
Program 10: Program to Demonstrate complex() Casting Function
complex_with_string = complex("1")
complex_with_number = complex(5, 8)
print(f" Result after using string in real part {complex_with_string}")
print(f"Result after using numbers in real and imaginary part {complex_with_number}")
Output
Result after using string in real part (1+0j)
Result after using numbers in real and imaginary part (5+8j)
6. The ord() Function: The ord() function returns an integer representing Unicode code
point for the given Unicode character.
Program 11: Program to Demonstrate ord() Casting Function
unicode_for_integer = ord('4')
unicode_for_alphabet = ord("Z")
unicode_for_character = ord("#")
print(f"Unicode code point for integer value of 4 is {unicode_for_integer}")
print(f"Unicode code point for alphabet 'A' is {unicode_for_alphabet}")
print(f"Unicode code point for character '$' is {unicode_for_character}")
Output
Unicode code point for integer value of 4 is 52
Unicode code point for alphabet 'A' is 90
Unicode code point for character '$' is 35
7. The hex() Function: Convert an integer number (of any size) to a lowercase
hexadecimal string prefixed with “0x” using hex() function.
Program 12: Program to Demonstrate hex() Casting Function
int_to_hex = hex(255)
print(f"After Integer to Hex Casting the result is {int_to_hex}")
Output
After Integer to Hex Casting the result is 0xff
8. The oct() Function: Convert an integer number (of any size) to an octal string prefixed
with “0o” using oct() function.
Program 13: Program to Demonstrate oct() Casting Function
int_to_oct = oct(255)
print(f"After Integer to Oct Casting the result is {int_to_oct}")
Output
After Integer to Oct Casting the result is 0o377
The type() Function and Is Operator
The syntax for type() function is, type(object)
The type() function returns the data type of the given object.
1. >>> type(1)
<class 'int'>
2. >>> type(6.4)
<class 'float'>
3. >>> type("A")
<class 'str'>
The type() function comes in handy if you forget the type of variable or an object during
the course of writing programs.
The operators is and is not are identity operators. Operator is evaluated to True if the
values of operands on either side of the operator point to the same object and False
otherwise. The operator is not evaluates to False if the values of operands on either side of
the operator point to the same object and True otherwise.
1. >>> x = "Sindhi"
2. >>> y = "Sindhi"
3. >>> x is y
True
1. >>> x = "Sindhi"
2. >>> y = "SINDHI"
3. >>> x is not y
True

Dynamic and Strongly Typed Language


Python is a dynamic language as the type of the variable is determined during run-time by
the interpreter. Python is also a strongly typed language as the interpreter keeps track of all
the variables types. In a strongly typed language, you are simply not allowed to do
anything that’s incompatible with the type of data you are working with. For example,
1. >>> 5 + 10
15
2. >>> 1 + "a"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
In Python, Traceback is printed when an error occurs. The last line tells us the kind of
error that occurred which in our case is the unsupported operand type(s).

You might also like