0% found this document useful (0 votes)
2 views74 pages

PDF&Rendition 1

The document outlines a course on Programming in Python, detailing its structure, learning objectives, and content across five units, including topics like data types, control statements, and file handling. It emphasizes the importance of Python in various domains such as web development, data analysis, and machine learning. Additionally, it provides resources for learning and installation instructions for Python software.

Uploaded by

shanmathi.012.s
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views74 pages

PDF&Rendition 1

The document outlines a course on Programming in Python, detailing its structure, learning objectives, and content across five units, including topics like data types, control statements, and file handling. It emphasizes the importance of Python in various domains such as web development, data analysis, and machine learning. Additionally, it provides resources for learning and installation instructions for Python software.

Uploaded by

shanmathi.012.s
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Course Code PROGRAMMING IN PYTHON Credits: 4

25ULU251

Breadth: Domain: Education and Entrepreneurship Cluster Core 1


Applications

Lecture: 4 hrs Tutorial :0 hrs per week Lab Practice: 0 hrs per week Lecture: 4 hrs per
per week week

Year: I Semester: I Admission Year:


2025-2026

Pre-requisite Basic Computer Skill

Links to other -
Courses

Learning Objectives (LO):

Develop a comprehensive understanding of Python programming, covering basic syntax, control structures,
functions, data types, and file handling, to enable effective problem-solving and application development.

Units Contents Required Hours

I: Introduction Comments in python-Doc strings-build in datatype-bool


and operators in datatype- sequence in python-sets- Literals in python-
python
determining the datatype of a variable Operators- arithmetic- Bit 12
wise operators- Membership Operator-Identity operator –
operator precedence and associativity- mathematical functions.

II Input and Command line arguments-control statement- Simple if-If else-If-


output & control elf-else statement-the while loop-the for loop-infinite loop-
statement and
nested loop-the break statement-continue-pass-assert- the 12
arrays in python
return statement-Arrays-types of arrays- mathematical
operation on array

III Creating strings-length of a string-repeating the string-


concatenation of string- comparing string- removing space 12

from a string- finding sub string- string are immutable -


String and formatting the string- sorting string-Function: defining a
function in function- calling a function - returning result from a
python function - returning multiple values from a function - formal
and actual arguments- default and keyword argument-
local and global variable-recursive function-lambda
function -modules -packages .

IV Creating list- updating the elements of a list- concatenation of

List and tuples in two lists- sorting the list elements- repetition of lists- nested lists-
python finding common elements in two list- Tuples: creating tuple
concatenation of two lists- sorting the list elements tuples-
12
accessing the tuple elements-basic operation on tuple nested
tuple-insert-modifying -deleting elements from a tuple.

V Operations on dictionaries-using for loop with dictionaries-

Dictionaries and converting list into dictionary- Types of files in python- opening 12
file in python a file - closing a file- working with binary files.

Course Focuses Course addresses the Cross cutting issues Course relevance to
on
Professional Ethics Global need
Employability

Learning Resources:

Recommended Texts

1. [Link] Rao, “Core Python Programming”, DreamTech Press, 2021, ISBN 10-9390457157.

Unit I : Chapter 3,4 Unit


II : Chapter 5,6,7 Unit III :
Chapter 8,9 Unit IV :
Chapter 10 Unit V :
Chapter11,17

Reference Books: 1.

ReemaThareja, “Python Programming using problem solving approach”, First Edition, 2017, Oxford
University Press. 2.
[Link], “A primer to python programming”, Notion Press, 2022, ISBN 13-979-
8888497821. 3.
Wesley Chun, “Core Python Programming” , 3rd Edition 2015, Pearson, ISBN: 10-9332555362

Web Resources:

1) [Link]
2) [Link]
3) [Link]
4) [Link]
[Link]
Programming in Python
UNIT-I
Introduction to Python and installation:

Python is a widely used general-purpose, high level programming


language. It was initially designed by Guido van Rossum in 1991
and developed by Python Software Foundation. It was mainly
developed for emphasis on code readability, and its syntax allows
programmers to express concepts in fewer lines of code.
Python is a programming language that lets you work quickly and
integrate systems more efficiently.
There are two major Python versions- Python 2 and Python 3.

• On 16 October 2000, Python 2.0 was released with many new


features.
• On 3rd December 2008, Python 3.0 was released with
more testing and includes new features.

Beginning with Python programming:

1) Finding an Interpreter:
Before we start Python programming, we need to have an interpreter
to interpret and run our programs. There are certain online
interpreters like [Link] [Link] or
[Link] that can be used to start Python without installing
an interpreter.
Windows: There are many interpreters available freely to run Python
scripts like IDLE (Integrated Development Environment) which is
installed when you install the python software from
[Link]

2) Writing first program:


# Script Begins
Statement1
Statement2
Statement3
# Script Ends
Differences between scripting language and programming language:

Why to use Python:

The following are the primary factors to use python in day-to-day life:

1. Python is object-oriented
Structure supports such concepts as polymorphism,
operation overloading and multiple inheritance.
2. Indentation:Indentation is one of the greatest feature in python
3. It‟s free (open source)
Downloading python and installing python is free and easy
4. It‟s Powerful
 Dynamic typing
 Built-in types and tools
 Library utilities
 Third party utilities (e.g. Numeric, NumPy, sciPy)
 Automatic memory management
5. It‟s Portable
 Python runs virtually every major platform used today
 As long as you have a compaitable python
interpreter installed, python programs will
run in exactly the same manner, irrespective
of platform.
6. It‟s easy to use and learn
 No intermediate compile
 Python Programs are compiled automatically to
an intermediate form called byte code, which the
interpreter then reads.
 This gives python the development speed of
an interpreter without the performance loss
inherent in purely interpreted languages.
 Structure and syntax are pretty intuitive and easy to grasp.
7. Interpreted Language
Python is processed at runtime by python Interpreter
8. Interactive Programming Language
Users can interact with the python interpreter directly for writing
the programs
9. Straight forward syntax
The formation of python syntax is simple and straight forward
which also makes it popular.

Applications of Python:
10. Although the original idea of developing Python is simple and
easy to use language, its efficacy and evolution made it a popular
programming language. Now it has been used in a variety of
domains and different packages have been developed for
different applications. The following are the domains using
Python language.
11. Python is exclusively used in web development. A lot of
frameworks are available for the design of the dynamic website.
For eg. Django, Flask, Web2py are the popular frameworks used
for the purpose of web development.
12. Scientific and numeric computing is one of the important
domains which is used in various scientific and engineering
applications. Python comes with handy scipy, numpy packages
for efficient processing.
13. Game Development is one of the popular domains and a lot of
people are using pygame for developing 2D and 3D games.
14. Data Analysis is another new-age technique used in the world to
analyze data for interpreting the same. Pandas are one of the
notable packages used in Python for data analysis
15. Machine Learning is a domain where the data are analysed to
predict new information. Packages like scikit-learn are
extensively used in Python.
16. Besides Python is extensively used in Scripting, Network
Programming, GUI Programming, Database Programming,
Image Processing, Internet Programming and Information and
Text Retrieval.
[Link] Version Release Date
1 Python 2.0.1 June’22,2007
2 Python 2.6 Oct’02,2008
3 Python 3.0 Dec 3,2008
4 Python 3.5.1 Dec‘7,2015
5 Python 3.7.1 Oct’20,2018
6 Python 3.8.1 Dec ’18,2019
7 Python 3.9.1 Dec’7,2020
8 Python 3.10.0 Oct’4,2021

Installation:

There are many interpreters available freely to run Python scripts


like IDLE (Integrated Development Environment) which is installed
when you install the python software from
[Link]
Steps to be followed and remembered:

Step 1: Select Version of Python to Install.


Step 2: Download Python Executable Installer.
Step 3: Run Executable Installer.
Step 4: Verify Python Was Installed On Windows.
Step 5: Verify Pip Was Installed.
Step 6: Add Python Path to Environment Variables (Optional)

Working with Python

Python Code Execution:

Python‟s traditional runtime execution model: Source code you type


is translated to byte code, which is then run by the Python Virtual
Machine (PVM). Your code is automatically compiled, but then it is
interpreted.
Source Byte
code Runtime

PVM

[Link] [Link]

Source code extension is .py

Byte code extension is .pyc (Compiled python code)

There are two modes for using the Python interpreter:


• Interactive Mode
• Script Mode

Running Python in interactive mode:

Without passing python script file to the interpreter, directly execute


code to Python prompt. Once you‟re inside the python interpreter,
then you can start.
>>> print( “ Hello world”)
Hello world

# Relevant output is displayed on subsequent lines without the >>>


symbol

>>> x=[0,1,2]

# Quantities stored in memory are not displayed by default.

>>> x

#If a quantity is stored in memory,

typing its name will display it. [0, 1, 2]


>>> 2+3

The chevron at the beginning of the 1st line, i.e., the symbol >>> is
a prompt the python interpreter uses to indicate that it is ready. If the
programmer types 2+6, the interpreter replies 8.

Running Python in script mode:

Alternatively, programmers can store Python script source code in


a file with the .py extension, and use the interpreter to execute the
contents of the file. To execute the script by the interpreter, you have
to tell the interpreter the name of the file. For example, if you have a
script name [Link] and you're working on Unix, to run the script
you have to type:

python [Link]

Working with the interactive mode is better when Python


programmers deal with small pieces of code as you can type and
execute them immediately, but when the code is more than 2-4 lines,
using the script for coding can help to modify and use the code in
future.

Example:
Python Fundamentals
Python Fundamentals deal with the basic building blocks of creating scripts in
python. It includes the structure and semantic matters, identifiers, variables,
statements, operators and expressions. This is the basis for developing simple
python scripts.

Structure of a Python Program


Module Documentation
Every python program is considered as a module. The first statement of any
python script normally starts with documentation about the program. The
documentation part is useful for reference. It includes the author who develops
the code, date, purpose and formulas if any. These details are given by using
comments in python. Documentation of the code describes its functionality and
usage to the users.
Import Module
Modules are nothing but a python file and it contains executable statements
(blocks of code), class definition and declaration, function definition and any
combinations of these portions. The name of the file acts as a module name. The
purpose of the module is the reusability of the code. One module can be used
within another module by importing it.
Global Variable Declarations

The variables which are all used throughout the program either inside the
function or outside the function are called global variables. Those variables
should be initialized in this part.

Class Definitions
Python allows object-oriented programming also. The user-defined data type
which includes both data members and function members are called classes. Class
definitions occupy the fourth part of the structure.
Function Definition

The block of code that has a name assigned to it and performs the specified
task is called function. Function definition must be introduced before the main
program code.

Main Program Body


The actual program that contains different types of statements is started from
this part. The only compulsory part in any Python script is main program. The
execution of the python script starts from the main program. The remaining parts
are all optional.
Example: Stucture of a Python program
#Module Documentation starts here
#Date: [Link]
#Purpose: To show the structure of Python Program

#import statement -Optional


import random

#Global Variables -Optional

#Class Definitions- Optional

#Function Definition - Optional


def generate_random_nos(start,end):
'''Reads start & end value & Generates a random number'''
return([Link](start,end))

#Main Program Starts Here -Compulsory

number1=int(input("Enter any Positive integer :"))


number2=int(input("Enter one more Positive int:"))
square=number2*number2

print("Random Number is:",generate_random_nos(number1,number2))

print("Square of ",number2,"is:",square)

The above program shows the structure of the python Program. The Python
scripts can be developed with main program alone. But it is advisable to have
module documentation. The example program shows the position of each part of
the program. The execution starts with the main program. Normally, it follows a
bottom-up approach. The program reads two positive integer numbers. Then it
calculates the square of the second number. It then calls the function to generate
a random number and print it. Finally prints the square of the second number
given.
The output of the program is
Enter any Positive integer: 10
Enter one more Positive int: 20
Random Number is: 11
Square of 20 is: 400

Syntax and Semantics


The statements in python take different forms like sequential statements,
decision making statements and looping statements etc. The structure of the
statements in computer language is called syntax. Every statement must be
created based on the syntax of the language.
Comment statement

Comments are a single line of text placed in different parts of the program
based on the requirement. Comments help the reader to understand the code and
its purpose without actually interpreting the statement. It is basically a short
description. The comments are introduced with the #(hash/pound) symbol. The
python interpreter ignores the statement that is followed by #. The comments are
used for future reference. Normally it includes the basic information (see
3.1)along with a small note about the program and formulas if any.
Program : Display Welcome message with comment statement

#Author: Name

#Date : [Link]

#Display the Message 'Hello'

print("Hello! Welcome to Python Programming")

The program shows module documentation (comments) with simple print


statements. The statements started with # are all ignored and the message string
in the print statement alone will be printed as below

Hello! Welcome to Python World


>>>
Advantages of Comment statement
 Code Description: Comments are used to explain specific parts of the
code.
 Algorithmic Description: It is possible for the developers to provide the
algorithm implemented in the script and can specify the purpose of using
the algorithm.
 Tagging or Labelling: Labels can also be provided to indicate issues to
be improved in the program.
Multiple statements in a line (;)

The statements are introduced one by one. If the statements are too small in
length, then one can use more than one statement in a single line. This can be
done with a semicolon(;).
Example
>>>a=5; b=7.0; c='Hello'
Block of code or Suites

A group of individual statements can be combined together to form a single


code block under some specific circumstances. Such a block of code is
called suites in Python. Compound or complex statements like if, while, def, and
class, require a header line and a suite.
Example
if expression:
Statement_01
Statement_02 ... Suite_01
Statement_0n
elif expression:
Suite_02
else:
Suite_03
Indentation

Python follows a spacing style, called indentation. Instead of using open


and close curly braces ({}) to represent blocks of code, Python follows
indentation. By default, the indentation leaves four spaces. It can also be changed
by the code developer. Indentation is represented by using the colon (:) symbol
at the end of the header of each block. The statements inside the block
automatically leave four spaces until it is de-indented. After the last statement of
the suite, it should be de-indented. No braces are used to represent blocks of code
as in C/C++/JAVA languages. The number of spaces in the indentation will be
varying, but all statements within the block must be indented with the same
amount of blank spaces.
Example
while expression:
Statement_01 #Statements with indentation
Statement_02
Statement_03
statement_x #statement with de-indentation
Program : Usage of Indentation

#Usage of Indentation
#Program: Read a number
#check whether it is a positive number
num=int(input("Enter a Number:"))
if num>0: #indent statement
print("The given number", num,"is POSITIVE")

The program shows how indentation is used to represent blocks of code. With
indent, the next line will be started automatically by leaving 4 spaces by default.
The output of Program is shown below
Enter a Number: 120
The given number 120 is POSITIVE
>>>
Program :De- Indentation
#Usage of Indentation

#Program: Read a number

#check whether it is a positive number

num=int(input("Enter a Number:"))

if num>0:

print("The given number", num,"is POSITIVE") # de-indent statement

The program shows indentation. If the developer of the code does not follow the
default 4 spaces of indent, it will be called as de-indentation. It is given in Fig. It
leads to an error that is specified in below fig.

Fig: De-Indentation Error


Continuation Line (\)

Some statements may occupy more than one line. To indicate the continuation
of the current statement to the next line the continuation character \ (Backslash)
is used at the end of the current statement.
Example
A= b*c+(x-2*y) \
*(x%2)-36
Doc Strings

 Docstring is a string literal that normally occurs in the first statement of


any code block like class definitions, function definitions, method
definitions etc. It may be given anywhere in the program that acts as
documentation. It is useful for the program developers to document
their code during the development of code.
 It is represented using triple quotes ('''’single triple quotes''' or " " "
Double triple quotes " " ")
 There are two types of docstrings. Single line docstring and multi-line
docstring.
 Docstrings can be accessed using the __doc__ attribute.

Program : Usage of Doc string

#Usage of docstring

def square(n):
'''Takes a number n & returns the square of n'''
return n**2
#Main Program
print("Square of 25 is:", square(25))
print("Doc String:",square.__doc__)
In program docsting is introduced below function definition to specify the
purpose of the function. It is possible to retrieve the docstrings in the program
using functionname._ _ doc _ _ attribute.
Output:
Square of 25 is: 625
Doc String: Takes a number n & returns the square of n
>>>
Identifiers
The name used to identify various objects like variable, function, class, module
and others is called an identifier.
Identifier naming conventions in Python:

a) Module names and package names are written in lowercase letters.


b) Global variables and constants are specified using upper case letters.
c) Method names and function names are written with lowercase letters.
d) Class names start with an uppercase letter and all other identifiers with a
lowercase letter. Example: Student_info
e) Starting an identifier with a single leading underscore indicates that the
identifier is meant to be private. Example: _sum indicates the variable sum
is private.
f) Starting an identifier with two leading underscores indicates a strongly
private identifier. It is useful to hide the data. Example: _ _total
g) If the identifier starts and ends with two underscores, then the identifier is
said to be a language-defined special name. Example: __ init__ indicates
the initialization method in python class definition.
Reserved Words:

Reserved words are those words that are reserved by the language itself for
specific purpose. A reserved word is "reserved for use as a keyword". The terms
"reserved word" and "keyword" are often used interchangeably. They cannot be
used as an identifier such as the name of a variable, function, or label. All the
Python keywords contain lowercase letters only.
Table Reserved Words in Python
input print format del main
if else elif for while
break continue pass def return
lamda global is in not
and or class with Open
try except finally assert type

Variables

An object whose value is changed during the execution of the program is called
a variable. A variable is a name that represents a value stored in the computer’s
memory. Based on the data type of a variable, the interpreter allocates memory
and decides what can be stored in the reserved memory. Therefore, by assigning
different data types to variables, the user can store integers, decimals or characters
in these variables.
Variable Naming conventions (rules):

a) An identifier starts with a letter A to Z or a to z or underscore.


b) The successive characters may be letters or digits (0 to 9).
c) The only allowable special character is an underscore (_).
d) No other special characters such as $, @ and! are allowed.
e) Case sensitive.
f) Variables can be of any length
Python is a case sensitive programming language. Thus, the variable basic_pay
and Basic_pay are two different identifiers in Python. The variable name must be
a meaningful one.
Tip: Python’s keywords cannot be used as a variable name.
Example
Valid variables: A1, basic_pay, name, roll_no, data1
Invalid variables: 5_Add, $small, (s_name, if
Variable Assignments:

Python is a dynamically or loosely typed language. No pre-declaration of a


variable is necessary. But in tightly coupled languages like C/C++ each and every
variable must be declared before they are used in the program. For example, in C
language the first step is to declare variables with a data type. In python, the
variables need not be declared but they are initialized with values on assignment.
Assignments are performed using the equal sign (=). It is also known as an
assignment operator. Syntax:
variable_name = value

Example
counter=0 #integer assignment
name=’Ram’ #string assignment
kilometres=1.069*miles #floating point assignment
a=a+1 #increment assignment

Python uses different forms of assignment statements. They are


a) Augmented Assignment
b) Multiple Assignment
c) Multuple Assignment
Augmented Assignment
The equal sign can be combined with an operator and the resulting value is
reassigned to the existing variable. It is called an augmented assignment. It is
useful when the left side of the variable is the same as that of one of the variables
on the right side of the expression.
Example
x=x+1 can be written as x+=1

Augmented assignment refers to the use of operators. The arithmetic and


bitwise operators can be used for augmented assignment.. It implies both an
operator and an assignment. += -
= *= /= %= **= <<= >>= &= ^= |= . The most
significant difference between the normal assignment and augmented assignment
is that the first object is examined only once.

Example
>>>a=8
>>>b=11
>>>a=a+b
The above statement show a normal assignment that uses the variable ‘a’ twice
both in the left and rigt side of the equal sign(=).
In the augmented assignment, the variable ‘a’ can be used once
>>>a=8
>>>b=11
>>>a += b
Multiple Assignments
If more than one variables need to be initialized with the same value, they can
be initialized with a single Python statement. The process of assigning a single
object to multiple variables is called Multiple Assignment.
Syntax:
variableObject1=variableObject2=variableObject3=value
Example
>>>a=b=c=3.0
A floating-point object is created with values 3.0 and a, b and c are all assigned
the same reference to that object.

>>>x=y= 3*c

The objects x and y takes the value of the expression 3*c. The expression is
evaluated and the result is assigned to multiple objects x and y.

Multuple Assignment
Instead of assigning individual objects with values in a separate statement,
more than one variable objects can be assigned with more than one value in a
single statement. It is called a multuple assignment statement.
Example
>>> x,y,z=36,45.902,"PYTHON"
>>> x
36
>>> y
45.902
>>> z
'PYTHON'
>>>

In the above code, one integer object (with value 36), one floating-point object
(with value 45.902) and one string object (with value ‘PYTHON’) are assigned
to x, y and z respectively. Parentheses are normally used to denote tuples, and
although they are optional. They make the code easier to read.
Example for multiple assignments with paranthesis
>>> x,y,z=(36,45.902,"PYTHON")
>>> x
36
>>> y
45.902
>>> z
'PYTHON'
>>>
To interchange any two values in the C language, we need to use a temporary
variable.
Example in C Language:
#include<stdio.h>
void main()
{
int a=60, b=80, t;
t=a;
a=b;
b=t;
printf(“a=%d, b=%d”,a,b)
}

Output:
a=80, b=60

But in Python language to swap the values of the variables, multiple


assignments can be used.

Program : code for multiple assignment

#swap two numbers without temporary variables


#uses multiple assignment
a=80; b=100
print("Before Swap")
print("a:",a,"\t b:",b)
a,b=b,a #multiple assignment
print("After Sap")
print("a:",a,"\t b:",b)

Initially a=80 & b=100. After swapping, a =100 and b=80. It is done in a single
multiple assignment statement.

The output is generated as below


Before Swap

a: 80 b: 100

After Sap

a: 100 b: 80

>>>
Tips:
 Variables need not be declared before they are used
 No need to declare variable types.
 No memory management on the programmers' part
 Variable names can be "recycled"
 del statement allows for explicit "deallocation"

Python Objects
Python uses object model concepts for storing data. So everything is treated as
an object in Python. Any construct that contains any data type of value is called
an object.
For example the variable, the number and the list variable are all called objects.
Every Python objects have the following three characteristics:
 An identity
 Type
 Value
Identity: The object’s identifier is a unique value. It is an address of the
memory location of that object. The unique identifier differentiates an object from
all others. It is obtained using the id () built-in function. id () function returns
the address of the memory location.
Type: An object's type indicates the data type of an object. The type() built-in
function is used to find the data type of a Python object. Since types are also
objects in Python.
Value: Value is a data item assigned to an object.
Program: Python objects characteristics
>>> x= 345
>>> id(x) # returns address of x
2920180680848
>>> type(x) #gives data type of x
<class 'int'>
>>> x #gives value in x
345
>>>

Data Types
In programming languages, the data type is a classification that represents the
type of value a variable takes and performs operations on it. A data type is simply
a set of values and the allowable operations on those values. Python supports a
set of basic (built-in) or standard data types and some auxiliary types. Most
applications generally use the standard types. The standard types are referred to
as "primitive data types". One of the features of Python related to data type is
dynamic typing. In dynamic typing, there is no need to declare the type of the
variable. The value is assigned to the variable object. The interpreter predicts the
type of the variable from the value assigned to it. It also accepts the re-assignment
of variables with different types.

Example
Program: dynamic typing
a=33.45
print("a is:",a)
print("Data type of a is:",type(a))
a='Excellent'
print("a is:",a)
print("Data type of a is:",type(a))

Object ‘a’ initially takes a float value. Later it is assigned with a string type of
data. Both are accepted by the object. The nature of changing the type and value
of the object is termed as dynamic typing.

Output
a is: 33.45
Data type of a is: <class 'float'>
a is: Excellent
Data type of a is: <class 'str'>
>>>
Standard Data types are grouped into five categories.
They are
a) Numeric Data Types
b) Sequences
c) Mappings
d) Sets
e) Others

Fig: Classifications of Data Types


Numeric Data Types

It includes all the forms of numbers related types. It is classified into


 integer
 long
 float
 complex
Integer (int):
Integers are the common numeric type. It includes whole numbers with a
positive or negative sign. The range of integers varies from -231 to +230. It is
equivalent to -2, 147,483,648 to 2,147,483,647. It takes 4 bytes of storage
location.
Integers are normally represented in decimal format (base 10), but they can
also be specified in Octal (base 8) or Hexadecimal (base 16) formats. Octal values
have a"0" prefix, and hexadecimal values have either "0x" or "0X" prefixes.
Examples
48, -567 #Integers
0X3A, 0x96F #Hex numbers
0476 #Octal Numbers
Long Integer (long):
Longs are a superset of integers. They are useful when the application
requires integers that exceed the range of integers. Long integers are denoted by
the letter "L", uppercase (L) or lowercase (l), appended to the integer's numeric
value. Values can be expressed in decimal, octal, or hexadecimal.

Examples
16384L -0x4E8L 017L -2147483648l 052144364L
299792458l 0xDECADEDEADBEEFBADFEEDDEAL -5432101234L

Tip: Python long integers are different from other language long integers. In
other compiled languages long integers are restricted to 32- or 64-bit sizes,
whereas Python longs are limited only by the amount of (virtual) memory in the
machine.
Float (Floating Point numbers):
Floats are represented in fractional or scientific notations. It takes 8-byte
(64-bit) values. 52 bits are allocated to the mantissa, 11 bits to the exponent and
one bit to the sign. It gives the range ± 10308.25. Floating-point values are
denoted by a decimal point (.) in the appropriate place. In scientific notation, the
number has four parts. They are mantissa, the letter ‘e’ or ‘E’ that represents the
exponent followed by positive (+) or negative (-) signs and the exponent value.
The absence of a sign indicates a positive exponent.
In 4.3e25, 4.3 is a mantissa, the letter ‘e’, absence of sign indicates positive
power and the exponent value 25.

Examples
Floating point numbers : -5.555567119, 0.0978, 123.78654
Scientific notation: 9.384e-23, 4.2E-10, -1.609E-19
Complex Number:
A complex number is an ordered pair of floating-point real numbers (x, y)
denoted by x + yjformat where xis the real part and yis the imaginary part.
Imaginary numbers by themselves are not supported in Python. They are always
paired with a real part of 0.0 to make a complex number.

Syntax
Real+Imaginary j
where
 Both real and imaginary components are floating-point values
 The imaginary part is suffixed with the letter "J" . It may be a lower case
letter (j) or uppercase letter(J)
Examples
64.375+1j
4.23-8.5j
0+1j
Attributes of Complex Numbers:

Data Attributes:
[Link]: It gives the real component of complex numbers.
[Link]: Displays the imaginary component of complex numbers.
Method Attribute:
[Link]() : Returns complex conjugate of num

Program: Example code for complex number attributes


>>> acomplex=-8.55+1.78j
>>> acomplex
(-8.55+1.78j)
>>> [Link]
-8.55
>>> [Link]
1.78
>>> [Link]()
(-8.55-1.78j)
>>>

Sequences
The data structure that is organized in an ordered format is called
sequences. It includes String, List and Tuple. Data structures indicate the
organizing collection of data items in a specific format.
Strings
The collection of characters enclosed between quotes is known as Strings.
Python allows three forms of quotes
 Single Quotes
 Double Quotes
 Triple Quotes
Pair of single and double quotes represents string whereas pair of triple single
quotes or double quotes represents documentations.
Program: Example code for string implementation

There is no difference between the usage of single quotes and double quotes to
represent strings. Single quotes are not useful to represent apostrophe commas
whereas double quotes can be used.
Program: apostrophes inside single quotes
>>> print('Welcome to Python's World')

SyntaxError: invalid syntax


>>> print("Welcome to Python's World")
Welcome to Python's World
>>>
When a string with apostrophe comma is enclosed using single quote, it leads to
error as shown in program. Because apostrophe comma in considered as single
quote.
Instead of apostrophe comma the string with single quote can be enclosed using
double quote or the apostrophe comma can be introduced with backslash (\’).
Example
>>> print('Welcome to Python\'s World')
Welcome to Python's World
>>>
Triple Quotes are used to represent multi-line documents. Any number of
statements enclosed between triple single quotes or triple-double quotes is known
as documentation statements.
Example
>>> '''This program aims to develop Paybill for Employees
with following constaints
Basic Pay Dearness Allowance
Less than 15000 10%
15000 to 25000 12% '''

List
A data structure that contains different types of data items separated by
commas and enclosed between square brackets ([]) is called Lists. Lists are
similar to arrays in C except that all the items belonging to a list can be of different
data types. Lists are mutable objects. It means that the data items within the list
can be modified.
The values stored in a list can be accessed using the slice operator ([ ] and [:]).
The list index starts from 0 and ends with the total number of elements in the list
-1. It has its own operators, functions and methods.

Program: List implementation


#List Data structure
list_items1 = [36,45.0,"JAVA",3+5j]
list_items2 = [33.789,456]
print("Contents of List_items1 are :", list_items1)
print("The First item/0th item in the list is:",list_items1[0])
print(list_items1[1:3]) #prints 1st & 2nd elements from list
print(list_items2*2) # repetition operator *
print(list_items1[2:]) #prints 2nd item to last item
print (list_items1+list_items2) # concatenation of lists with +

The above program shows the list data structure creation, accessing elements
and operators.
Output:
Contents of List_items1 are: [36, 45.0, 'JAVA', (3+5j)]
The First item/0th item in the list is: 36
[45.0, 'JAVA']
[33.789, 456, 33.789, 456]
['JAVA', (3+5j)]
[36, 45.0, 'JAVA', (3+5j), 33.789, 456]
>>>

Tuple
A tuple is another sequence data type that is similar to the list. A tuple consists
of a number of values separated by commas. Tuples are enclosed within
parentheses. Tuples are immutable objects. The data items within the tuple cannot
be modified.
The main differences between lists and tuples are:
 Lists are enclosed in brackets ( [ ] ) but Tuples are enclosed in
parentheses(( ))
 Lists are mutable means that their elements and size can be changed. But
tuples are immutable means that their elements cannot be modified.
They act as read only lists.
Program: Tuple implementation

#Tuple Data structure

tuple_items1 = (36,45.0,"JAVA",3+5j)
tuple_items2 = (33.789,456)

print("Contents of Tuple_items1 are :", tuple_items1)


print("The First item/0th item in the Tuple is:",tuple_items1[0])
print(tuple_items1[1:3]) #prints 1st & 2nd elements from tuple
print(tuple_items2*2) # repetition operator *
print(tuple_items1[2:]) #prints 2nd item to last item
print (tuple_items1+tuple_items2) # concatenation of tuple with +

The above program shows the creation of tuple, accessing elements from tuple
and operators applied to tuple object.

Output:
Contents of Tuple_items1 are : (36, 45.0, 'JAVA', (3+5j))
The First item/0th item in the Tuple is: 36
(45.0, 'JAVA')
(33.789, 456, 33.789, 456)
('JAVA', (3+5j))
(36, 45.0, 'JAVA', (3+5j), 33.789, 456)
>>>
Mapping (Dictionary)

Mapping is an unordered data structure. The data items that are


arranged in the form of key-value pairs are called dictionary. Dictionary structure
in python follows a hash table type. They work like associative arrays. A
dictionary key can be almost any Python type but are usually numbers or strings.
Values can be any arbitrary Python object. Dictionaries are enclosed by curly
braces ({ }) and values can be assigned and accessed using square braces ([]).
Program: Dictionary implementation
# Dictionary Data Structure
dict1 = {} # empty dictionary

dict1['one'] = 1 #add 'one' as key & 1 as value

dict1['two'] = 2

dict1['three']=[6,7]

print ("Dictionary contents are:",dict1)

#accessing elements with its key


print ("Dictionary wi th key three is:",dict1['three'])

Dictionary can be created with or without elements as in program 3.12. The


elements in the dictionary are accessed using the key. The above program
generates the output as
Dictionary contents are: {'one': 1, 'two': 2, 'three': [6, 7]}
Dictionary wi th key three is: [6, 7]
>>>

Set
A Set is an unordered collection of data with no duplicate elements. A
set supports operations like union, intersection, or difference. The function set()
creates a new set. It performs operations equivalent to mathematical set
operations.
Example
>>>set1=set() #creates new set without elements
>>>set2=set(['a','b','c','d','e','d']) # creates set with elements
>>>print(set2)
{'d','e','a','b','c' } #set2 without duplication

Other data types

Boolean:

In the Python programming language, the Boolean data type is a primitive data
type having one of two values: True or False. This is a fundamental data type. It
is useful in conditional expressions.
Example
flag = True

None:
There is another special data type –None. Basically, the data type means non-
existent, not known or empty.
Example y=None
Data Type Conversion

During the program development, there may be the possibility to convert one
form of data into other forms. To convert between types, the type name can be
used as a function. There are several built-in functions to perform conversion
from one data type to another.

Table Data type conversion functions

Function Description Example


>>>x=35.90
The argument ‘x’ in float is converted >>>print( int(x))
int(x)
into integer 35

The argument ‘x’ either in integer or long >>>x=35


float(x) integer is converted into floating point >>>print( float(x))
number 35.0

complex(real, img) Creates a complex number >>>complex(3,5)


(3+5j)
Object x is convered to astring >>>x=78
str(x) >>>print(str(x))
representation.
'78'
The sequence object ‘x’is converted to a >>>x='any'
list(x) >>>print(list(x))
list.
['a', 'n', 'y']
>>>x='any'
Anysequence object‘s’ is converted into a
tuple(s) >>>print(list(x))
tuple.
('a', 'n', 'y')
An integer ’x’ is converted to a >>>print(hex(34))
hex(x)
hexadecimal string. '0x22 '
oct(x) An integer ‘x’ is converted to an octal >>>print(oct(34))
string. '0o42 '
Input-Output Statements

The input and output statements are used to receive data from the users and
display the outputs to the user

Input Statement

Input statement is used to read data fom [Link] for the program can be
read in three ways. They are
Static input
The value which is given as an input for the program can be assigned to the
variable using assignment operator (=) during the development of the program.
Example
a=34
b=128
Dynamic input
When the input is given during the execution of the program, it is called
dynamic input. The user can input their data during the execution time with the
help of the built-in functions input().
Syntax:
variable_object= input([“prompt string”])
where
 prompt string is the message string and is optional.
This function reads integer, float and string data only as a string. Data type
coercion is used to convert them into required types.

Program: Reaing data from user


# Input Statement: input()
name=input("Enter Your name:")
basic_pay=input("Enter Your basic pay:")
print("Name\t:", name)
print("Basic Pay\t:",basic_pay)
print ("Type of Name is :", type(name))
print("Type of Basic Pay is:",type(basic_pay))
Output of program is shown below
Enter Your name: Aarish Kumar
Enter Your basic pay: 30000
Name : Aarish Kumar
Basic pay : 30000
Type of Name is :< class ‘str’>
Type of Basic Pay is : <class ‘str’>
>>>

Pogram reads the name and basic_pay from the user and displays those data items.
The input() function reads all types of data only in the form of a string. So
basic_pay is also read as a string. Data type conversion is required with input()
function to read data in the expected type like integer, float etc.

Program: Reading data from user with data type conversion


# Input Statement: input() with data type coercion
name=input("Enter Your name:")
basic_pay=int(input("Enter Your basic pay:"))
print("Name\t:", name)
print("Basic Pay\t:",basic_pay)
print ("Type of Name is :", type(name))
print("Type of Baasic Pay is:",type(basic_pay))

Now the program generates below output


Enter Your name:Aarish Kumar
Enter Your basic pay:30000
Name : Aarish Kumar
Basic Pay : 30000
Type of Name is : <class 'str'>
Type of Basic Pay is: <class 'int'>
>>>
Output Statement

To display the data on the screen, Python uses print statements. The print
function normally displays a line of output.
Syntax:
print(variable_obj,variable_obj,…,sep=’separator’,end=’end’,file=[Link],
flush=false)
where
 variable_obj represents a variable that holds the value.
 sep represents the separator of values. It may be a blank space or any
delimiter.
 end indicates the end of the character. Generally, it is a newline (\n). Any
delimiter may also be used.
 the file represents the way of displaying output. Sys. stdout specifies the
console.
 flush is a boolean value that indicates whether a buffer is cleared or not.
 All the arguments except variable_object are optional
Program: Displaying output with print()
#output Statement: print()

num1=int(input("Enter a number:"))
num2=int(input("Enter one more number:"))

print (num1,num2,sep="\t")
print ("Number1:",num1, "Number2:",num2, sep="\n")

for i in range(1,6):
for j in range(i):
print(j, end='\t')
print("\n")

Multiple values can also be printed using a single print statement. When
multiple arguments are passed, they are automatically separated by a space when
they are displayed on the screen. If the developer of the program wants to
introduce the character as a separator between arguments, it will be introduced
using ‘sep’ argument as in program.

Output

Enter a number:7
Enter one more number:8
7 8
Number1:
7
Number2:
8
0

0 1

0 1 2

0 1 2 3

0 1 2 3 4

>>>
Expressions can also be directly incorporated into print() along with message
strings.
Below example shows printing values with message string.
>>> a=44
>>> b=12
>>> print("Multiplication of two numbers results:",a*b)
Multiplication of two numbers results: 528
>>>
Escape Characters
An escape characteris a special character that is used to introduce required spaces
or characters in the output. It is preceded by a backslash (\). It is always treated
as a string (enclosed between quotes) and also called as escape sequences.
Table Escape sequences

Escape Description
Character
New Line. Cursor is moved to the
\n
next line.
Tab. It moves the cursor to the next
\t
horizontal tab position
\v Vertical tab
\r Carriage return
\f Form feed
\” Double quote will be printed
\\ Back Slash character will be printed
\’ Prints single quote
\ooo Octal value
\xhh Hex value

Example

print('Sunday\t Monday\tTuesday\tWednesday\tThursday')

Output
Sunday Monday Tuesday Wednesday Thursday

Displaying Multiple Items (+ Operator)

Generally, the + operator is used to add two numbers. When the + operator is
used with two strings, it performs string concatenation. This means that it appends
one string to another.
Example
print('This is ' + 'one string.')

It will print
This is one string.

Formatted Outputs

The output of the program can be presented in several different forms. They
are
 Formatting with string modulo operator(%)
 Format() method

Formatting with string modulo operator (%)


The print statement is paired with the string format operator (%). It supports
string substitution. It requires a formatting symbol to specify the data type.

Syntax
print(‘String %format symbols’ % arg1,arg2,..)
The format symbol may take any one of the following symbols. It usually
represents the type of data.
Table Format Symbols

Format Conversion
Symbol
%c Character value will be
printed
%s String value using str()
%r String value via repr()
%d (or)%i Signed decimal integer
%u Unsigned decimal integer
%o Octal integer
%x (or)%X Hexadecimal integer
%e (or) %E Exponential notation
%f (or) %F Floating point number
%% Print % character

Syntax of format placeholder


% [total digits] [.number of digits after decimal point] type
Integer 12 is represented as %2d
Float 34.8765 is represented as %7.4

Program: Example for Formatted outputs


x=240 ; x1=-22 ; y=349.20567
print ("we are at %d%%" % 100)
print ('Integer output: %d' % x)
print ('Integer output: %+i' % x)
print ('Integer output: %i' % x1)
print ('Octal Output of x : %o' % x)
print ('Octal Output of x : %#o' % x)
print ('Hex output with leading 0X is : %#X' % x)
print ('Real number : %f' %y)
print ('Exponent : %e' % y)
print ('Real : %5.1f' % y) #Usage of m.n

Output:

Format() function
The format () function is used to represent the way in which the value should
be displayed. It requires two arguments. The first one is the value to be displayed
and the second is the format specifier. The format specifier is a string that contains
special characters to represent the formatting of the given numeric value.
Syntax
format (variable_objetct, ’separator format specifier’)
where
 The separator is used to introduce required separators between objects.
 The format specifier requires precision and formatting character.
Formatting floats
The floating-point numbers are normally displayed with 12 significant digits
or more. Example,
>>> a=5; b=3.0

>>> a/b

1.6666666666666667
A simple division gives 17 digits as its output. So it is necessary to convert the
output into the required format.
Format to specific digits: it uses precision with format symbol ‘f’
>>>print(format(a/b,'.2f'))
1.67
.2f is the precision. It tells the number of digits after a fractional point. ‘f’ is a
format symbol for floating-point numbers.
Formatting floats with separators: it is used to include necessary separators with
numbers. The example shows a comma separator.
>>> print(format(20789.43789,',.2f'))
20,789.44
Formatting with Percentage:
To convert the given value into a percentage, the percentage symbol % will be
used instead of using format symbols like ‘f’. The % symbol multiplies the given
value by 100 and attaches % with it.
>>> print(format(mark_english,'.0%'))
71%
Formatting scientific notations: To represent the numbers in scientific notation
the format symbol ‘e’ or ‘E’ is used. The second argument is simply an ‘e’ or it
may be a precision followed by ‘e’. In both cases, it takes only 2 digits after the
sign.
>>> print(format(334821.3400089,'e'))

3.348213e+05

>>> print(format(334821.3400089,'.2e'))

3.35e+05

Formatting Integers
To format integers, the character ‘d’ is used as the format symbol and precision
is not required. Separators can be incorporated with numbers and additionally
width may be specified.

Example

>>>print (format (20789.43789,',.2f'))


20,789.44
>>>print (format(2530049876,'d')) #displays the number
2530049876
>>>print (format (2530049876,',d'))#displays the nuber with comma
2,530,049,876
##displays the number with 15 chars
>>>print (format (2530049876,'15d'))
2530049876
#displays the number with 15 chars with comma
>>>print (format (2530049876,'15,d'))
2,530,049,876
>>>
Operators
The operators in Python are classified into seven categories. They are:
1. Arithmetic Operators
2. Relational or Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
The operators are used to perform computations.
1. Arithmetic Operators

The arithmetic operators include operators to perform addition, subtraction,


multiplication, division, modulo division and exponentiation. The arithmetic
operators with operands form arithmetical expressions.
Table : Arithmetic Operators
Operat Operation Description Example
or
+ Addition Adds 2 or more >>> a=126.25
values >>> b=138.98
>>> a+b
265.23
- Subtractio Subtracts one >>>a=98;
n value from b=126
other >>> a-b
-28
* Multiplica Multiplies 2 or >>>a=98;
tion more values b=126
>>> a*b
12348
/ Division Divides one >>>a=98; b=126
value by other >>> a/b

0.777777777777
778
// Floor Divides one >>>a=47; b=6
Division value by other >>> a // b
7
and removes
fraction
% Modulo Gives >>> a=47; b=6
Division remainder of >>> a%b
division 5
** Exponenti Gives power >>> a= 13; b=2
ation for the given >>> a**b
base 169

The “/” operator and “//” operator performs division operations. But the
difference between them is the way in which they provide outputs. If the operands
are integer then division and floor division produce the same results. If the
operands are float, then division operation gives float output by performing
complete division but floor division makes the fraction to zero.

Example for the division of integer and float values

>>> a=17; b=3


>>> a/b
5.666666666666667
>>> a=17.0
>>> b=3.0
>>> a/b
5.666666666666667
>>>
The example assigns 17 to a and 3 to b. Both are integer values. By applying a
division operator it results in float output. In the case of float data like a=17.0
and b=3.0 also, division results in float output.

Program: Example for floor division of integer and float data


>>> a=17;b=3

>>> a//b

>>> a=17.0;b=3.0

>>> a//b

5.0
>>>
The difference between integer and float data by applying floor division (//) is
given in the above program. The floor division operator applied to integer data
results in integer output whereas the same operator applied to float data results in
truncation of fraction, that is the fraction is made zero.

Modulo Division

Modulo division operator gives the remainder of the division. The sign of
modulo division depends on the divisor, not the dividend.

Program: Example for modulo division


>>> 13%4
1
>>> -13%-4 # modulo divsion of negative numbers
-1
>>> -13%4
3
>>> 13%-4
-3
>>>
Tip: Mathematical computation of negative modulo division.
a mod b=a-c*b
a=-13 & b=4
c=-13/4=-3.25 => truncate decimal part results -3
-13 mod 4=-13 – (-3)*4=-13- (-12) =-13+12=-1
2. Relational or Comparison operators

The relational operators determine whether any relationship exists among the
operands.
For example, to check whether the first operand is greater than the second
operand, greater than operator is used. Relational operators result only Boolean
outputs (True or False).

Table Relational operators


Operator Description Example Output
< Less than >>>78<123 True
<= Lessthan or equal >>>78<=78 True
> Greater Than >>>145>123 True
>= Greaterthan or >>>23>=90 False
equal
== Equal >>>56==56 True
!= Not equal >>>34!=34 False
Example for the usage of relational operators
>>> a=45;b=56;
>>> a>b
False
>>> a == b
False
>>> a != b
True
>>> a < b
True
>>>
3. Logical Operators

The logical operators create compound expressions by combining more


than one relational expression. The logical operators provide Boolean outputs.

Table Logical operators


Operator Description Example Output
and It gives True 78<123 and 78>45 True
output, if all the
sub expressions
result Tue.
Otherwise it
results False.
or It gives True 78<78 or 78<43 False
output, if any
one or ll the sub
expressions
result Tue.
Otherwise it
results False.
not It reverses the not 145>123 False
output of the
resultant
expression. It
requires one
expression
only.

4. Assignment Operator

The assignment operator is equal to (=). Various types of assignment operators


have augmented assignment or shorthand assignment, multiple assignments and
mutable assignments.
5. Bitwise operators

Bitwise operators work on bits. It converts the given number into bits and
performs the specified operation.

Table Bitwise operators


Operator Description Function Example
>>>a=98; b=56
& Bitwise AND Binary operator. >>> a & b
If any one input
32
bit is 0, output
will be 0.
Otherwise
output will be 1.
| Bitwise OR Binary operator. >>> a | b
If any one input
122
bit is 1, output
will be 1.
Otherwise
output will be 0.
^ Bitwise Binary operator. >>> a ^ b
Exclusive OR If the input bits
90
are alternate (1
& 0), output will
be 1. Otherwise
output will be 0.
~ Negation It complement >>> ~a
every bit in the
-99
input. It’s a
unary operator.
One operand is
required.
<< Left Shift It left shifts the >>> a << 1
given number
196
by specified
number of
times.
>> Right Shift It right shifts the >>> a >> 1
given number
49
by specified
number of
times.

Example: Implementation of bitwise operators:

To perform bitwise operations, every digit should be converted into bits of


relevant format (8/16/32/64 bits) and then the operation is applied to every bit
combination.
a = 60 =0011 1100
b = 43 =0010 1011
--------------------------
a&b =40=0010 1000
a|b = 63= 0011 1111
a^b = 23= 0001 0111
~a = 1100 0011 #Complements every bit in the variable ‘a’

Tips: Left shift a number by one time is equivalent to multiplying the number
by 2. Similarly right shift a number by one time is equivalent to dividing the
number by 2.
6. Membership Operators

It is the special operator in python. It checks whether the specified value


is available in the sequence.
Table Membership operators
Operator Description Example
in Returns True, if the value >>>numList=[23,56,-
of the variable is a member 89,90.78,12]
of the specified sequence
>>> 56 in numList
else returns false.
True
not in Returns True, if the value >>>numList=[23,56,-
of the variable is not a 89,90.78,12]
member of the specified >>> 56 not in numList
sequence else returns False
false.

Program: Search for an element using membership operator

#Read a name and check whether it is a member of list of names

name_list=["Harish", "Manoj", "Raman", "Irfan"]


name=input("Enter a Name:")
if name in name_list:
print("Available")
else:
print("Sorry Not Available")

The example contains a list of names and reads a name from the user. Then it
checks whether the name provided by the user is a member or available in the list
of names. It displays “available” if the name is a member of the list otherwise
results in “Sorry Not Available”

Output
Enter a Name: Manoj
Available
>>>
The membership operator “in” can be used with conditional statements or can be
used directly as below.
>>> name_list=["Harish", "Manoj", "Raman", "Irfan"]
>>> name=input("Enter a Name:")
Enter a Name:Kishore
>>> name in name_list #in operator can be used directly
False
>>> name=input("Enter a Name:")
Enter a Name:Raman
>>> name in name_list
True
>>>
7. Identity Operators

Identity operators are also the special operators in Python. It compares the
memory locations of two objects. Memory locations of the objects can be
obtained from the id() method.

Table Identity Operators


Operator Description Example
is Returns True, if the memory >>> a=98; b=156;
locations of the objects are c=a
same else returns false. >>> a is b
False
>>> a is c
True
is not Returns True, if the >>> a=98; b=156;
memory locations of the c=a
objects are different else >>> a is not b
returns false. True
>>> a is not c
False

Program: Implementation of identity operators

>>> a=98; b=156; c=a


>>> id(a)
140725565579968
>>> id(b)
140725565581824
>>> id(c)
140725565579968
>>> a is c
True
The address of objects ‘a’ and ‘b’ are provided by id() function. Then the ‘is’
operator is applied to check whether both objects share the same address. If the
result is False then they occupy different memory locations. The object ‘c’ refers
to object ‘a’. When the identity operator is applied to objects ‘a’ and ‘c’, it gives
“True”. Because both of them share the same memory location.
Precedence and Associativity of Operators

The precedence gives the rules for the order of evaluation of operators in an
expression when they are not grouped with parenthesis. It is applicable for
complex expressions. If the expression has more than one operator, the conflict
arises for choosing which operator is first for evaluation. Python provides priority
for selecting the operators. It is given as follows

Table Precedence of Operators


Operator Precedence
Parenthesis () Highest -1
Exponent (**) 2
Bitwise not(~) 3
Unary + and Unary - 4
*,/,% 5
+,- 6
<< , >> 7
& 8
^ 9
! 10
Comparison, Identity 11
and Membership
operators
Logical not 12
Logical and 13
Logical or Lowest- 14
Example
In the first expression, parenthesis has the highest precedence. So it is
computed first and results in 12. Then it is multiplied by 3 to produce 36.
In the second example, there is no parenthesis. Two operators * and + are
available. If more than one operator is given, the system has to choose one among
them. Here precedence is used to select the highest precedence operator.
According to that * has higher precedence over +. So 3*5 is performed to produce
15 and then it is added with 7 to obtain the result 22.

Associativity

The associativity is the order of evaluation of an expression that contains more


than operators of the same precedence. If an expression contains more than one
operator of the same precedence, then it will be hard to select the order of
evaluation. Based on associativity, there are two possibilities. One is left
Associative and the other is right Associative. Left Associative operators start
their evaluation by grouping operators and operands from left to right. Right
Associativity starts its evaluation by grouping operators and operands from right
to left. Normally all the operators except the exponent are left-associative.
Right Associative Operators: Unary operators like unary +, unary -, negation
~, exponent **, logical not!.

Example
In the example, two operators division (/) and multiplication (*) are given. Both
are equal precedence operators. Now it is necessary to select the order of
evaluating the expression. The operators are left-associative (in the sense they
select the left side of its operand first and apply the operation on the right side of
the operand), so the expression is evaluated from left to right. 25/5 results 5.0.
Then it is multiplied by 3 to produce 15.0.
Image
The above example is for the right-associative operator. The exponentiation
operator takes the right side of the operand first and applies the operation on the
left side of the operator. 2**2 results 4. Then 3**4 produces 81.

Expressions

Operators combined with operands form the expressions. Python has a rich set
of operators. By using these operators with operands different sorts of expressions
can be formed.
Arithmetic Expressions

When the arithmetic operators are used with operands, arithmetic expressions
are formed. They are useful to perform mathematical computations.
Table 3-11 Examples for expressions
Mathematical Programming
Expressions Statement
7x 7*x
3ab(5x+6y) 3*a*b*(5*x+6*y)
𝐴 = 𝜋𝑟 2 A=3.14*r*r

Program: Implementation of Arithmetic expression

# Program: Simple interest calculation


#Formula simple-interest=principal-amount * no of years * interest/100

#read necessary inputs from user


p=float(input("Enter Principal Amount:"))
n=int(input("Enter Number of years:"))
r=int(input("Enter Rate of Interest:"))

#calculate Interest
simple_interest=p*n*r/100

#print the result


print("The Simple Interest is :",simple_interest)

The program aims to calculate simple interest. It requires principal amount,


number of years and rate of interest as its input. Then calculates simple interest
using the formula and produces the result.
Output
Enter Principal Amount: 15250
Enter Number of years: 3
Enter Rate of Interest: 5
The Simple Interest is: 2287.5
>>>

Relational Expressions

The relational operators with operands create relational expressions. The


relational expressions are used to check the relation between the operands and
provide Boolean outputs.

Program: Implementation of Relational expression


#Program : Biggest among two numbers

no1=int(input("Enter a number:"))

no2=int(input("Enter a second number:"))

if no1>no2:

print ("The biggest is :",no1)

else:

print("The biggest is:",no2)

The above program reads two numbers from the user and checks the biggest
number among the two.

Output
Enter a number: 345
Enter a second number: 239
The biggest is: 345
>>>
Enter a number: 54
Enter a second number: 1098
The biggest is: 1098
>>>

Logical Expressions

The logical operators with operands form logical expressions. The operands
should be relational expressions. It results in a Boolean outcome. It is used to
perform complex relational expressions.
Example
>>> a=23;b=49;c=12

>>> (a == b) or (a > c)

True
Bitwise Expressions

The bitwise operators with operands form bitwise expressions. Bitwise


operators are applicable to integers alone. When negative numbers are used, it is
converted into its equivalent 2’s complement form.

Program: Usage of bitwise expressions


UNIT-2

Control Structures
In Programming languages, the statements are categorized into two types
namely sequential statements and control flow statements.
Sequential statements: The set of statements that are executed in the order
one after another in which they are written is called sequential statements.
Control flow statements: The statements that alter the order of execution of
statements are called control flow statements or control structures.
The programs are generally written by using sequential statements. But in some
situations, it is necessary to decide which statement to be executed next based on
logical design. It leads to the introduction of control structures. It is represented
in two forms.
Selection or Decision making statements: The sequence of execution of the
statement is decided based on the condition mentioned in the current statement.
Loop or Repetition Statements: A set of statements are executed repeatedly
according to the logic of the program.
Selection or Decision Making Statements

The sequence of execution is decided by the conditions mentioned in the


current statement. This statement is made up of relational or logical conditional
expression(s). It checks the relation between the data and produces either True
or False outcomes. Based on that outcome the statement which is to be executed
next will be decided. Non zero or non-null value is considered as True and null
or zero is considered as False.
It is classified into

a. Simple if statement
b. if-else statement
c. Nested if statement
d. elif ladder
Simple if Statement

It is the simplest form of decision structure. The simple “if” statement contains
a relational or logical expression. It is used to compare data and then a decision
is made based on the result of the comparison.
Syntax:
if conditional_expression:
True-suite
Statement-in-sequence

The conditional expression in the ‘if’ clause header is evaluated first. If it


results true then True-suite will be executed. Then control moves to sequential-
statement. If the conditional expression produces false output, then the execution
begin from statement-in-sequence and the True-suite has been skipped. The True-
suite may have a single statement or more than one statement.

Fig Flowchat of simple if

If the true-suite contains a single statement, it may also be written in a single


statement as

if conditional-expression : statement

Example
if option==1: print “Good”

Example
Program : Usage of Simple if

1 #Read a number and check whether it is a negative number


2 num=int(input(“Enter any number:”))
3 if num<0: print(num,” is negative”)
4 print (“Done”)
if-else statement

if-else statement is called a two-way decision-making statement. Because it


consists of two blocks. One block of statements will be executed if the condition
is true and the other block will be executed if the condition is false.
Syntax:
if conditional-expression:
True-suite
else:
False-suite
Statement-in-sequence
The conditional expression in the “if” clause is tested. If it is true, the True-suite
of indented statements following the if clause is executed, and then control of the
program jumps to the statement that follows the if-else statement (statement-in-
sequence). If the condition is false, the false-suite which is followed by the else
clause is executed, and then control of the program jumps to the statement that
follows the if-else statement.

Fig Flowchart of the if-else statement

Program :Implementation of if-else

1 #Program to implement if-else


2 #Read a number & Check whether it is a odd or even
3 #Filename: [Link]
4 no=int(input("Enter a number:\t"))
5
6 if no%2==0:
print( "The given number",no,"is EVEN")
7 else:
8 print( "The given number",no,"is ODD")
9
10 print( "FOUND THE NUMBER TYPE")

The Program reads a number from the user and checks whether it is an odd
number or even number using the modulo division operator (%). If the remainder
of any number by 2 results in 0, then it will be an even number otherwise it is an
odd number. The “if” clause header has a conditional expression no%2 == 0. On
executing this relational expression, the boolean output will be generated. If True
is produced then the statement which is followed by header (True-Suit) will be
executed. In this example, it prints the result as Even. After the completion of
True-Suit, the control jumps to the statement which is in sequence with “if”. Here
it moves to Line number 9 and prints “FOUND THE NUMBER TYPE"
Output of Program 4.2 is given below
Enter a number: 34
The given number 34 is EVEN
FOUND THE NUMBER TYPE
>>>
If the conditional expression no%2 == 0 gives False output, then control jumps
to the else part of the statement and False-suit will be executed.
Example
Enter a number: 315
The given number 315 is ODD
FOUND THE NUMBER TYPE
>>>

Nested if statement

It is possible to test compound conditions using a decision structure. It can be


done by nesting if-clauses. If the ‘if’ statement is introduced inside the true block
of the if clause, it is called nested if. The nested if clause may be a simple if or
if..else statement.
Syntax:
if conditional-expression1:
True-suite-1
if conditional-expression2:
True-suite-2
else:
False-suite-2
else:
False-suite-1
Statement_in_sequence

The conditional_expression1 in the “if” clauseis tested. If it is true, the True-


suite statements of that “if” clause is executed. In nested if, the True-suit contains
an “if” clause within it. It has its true suit for the true outcome and may have a
false suit for a false outcome. The statements are executed according to
conditional-expression2. Finally, the statement that follows the “if” clause
(statement-in-sequence) will be executed.

Fig Flowchart of Nested if Statement


Example
Program : Implementation of Nested if

1 #Bank Trnsaction- Read an amount and withdraws it from account


2 min_balance=1000.00
3 available_balance=8000.00
4 wamount=float(input("Enter the amount to be withdrawn:\t"))
5 if available_balance > min_balance:
6 if available_balance-wamount > min_balance:
7 available_balance = available_balance -wamount
8 print ("Your withdraw Amount is:", wamount)
9 print ("Balance is :", available_balance)
10 else:
11 print("After withdrawing", wamount,"your balance goes below mnimum
balance")
12 print("So you are unable to withdraw")
13 else:
14 print ("Your balance is low. You can't withdraw")

The example program shows checking of the balance after withdrawing the
amount from the account. Every bank has been expecting the customer to
maintain a minimum balance in their account. Based on that, the minimum
balance in this example is Rs1000. The balance available in the account is say for
example Rs.8000. The customer has to input the amount to be withdrawn. If the
available balance is greater than the minimum balance then he/she is allowed to
withdraw. The above condition is introduced using a nested if statement. Line
number 5 checks for minimum balance against available balance. If it is true, the
available balance after withdrawal will be checked with a minimum balance. If
this is also true then the customer can withdraw the amount. Otherwise relevant
messages will be printed. It is given in line numbers 11 and 14. The two scenarios
are given as outputs below
Enter the amount to be withdrawn: 5000
Your withdraw Amount is: 5000.0
Balance is : 3000.0
>>>
Enter the amount to be withdrawn: 7500
After withdrawing 7500.0 your balance goes below mnimum balance
So you are unable to withdraw
>>>

if-elif-else Statement

A special case of the decision structure is the if-elif-else statement. The “if”
clause can be introduced inside the false block of the if statement also. It makes
the logic simpler to write. It is known as the elif ladder.
Syntax:
if conditional_expression_1:
True-suite_1
elif conditional_expression _2:
True-suite_2
….
else:
False-suite
statement_in_sequence

Similar to other if statements, the conditional_expression_1 as stated above in the


“if” clauseis tested first. If it is true, the True-suite_1 will be executed and the
control jumps to the statement which is in sequence with the “if:” statement. If
the boolean output of conditional_expression_1 is false, the else block of the
corresponding “if” statement will be selected for further processing. But in this
format else is combined with an “if” statement to form elif statement with usual
conditional_expression and its true block and/or false block. Based on the
outcome of conditional_expression_2 its corresponding true suite or false suite
will be selected for processing. After completing a false suite the statement that
follows the “if” clause (statement-in-sequence) will be executed and the
sequential execution of the program will be continued.

Fig- Flowchart of if-elif-else


Example
Program : Usage of if-elif-else
1 # Read 4 subject marks from user
2 #calculate result, average and grade
3 # using if-elif-else
4
5 mark1=int(input("Enter Mark1:\t"))
6 mark2=int(input("Enter Mark2:\t"))
7 mark3=int(input("Enter Mark3:\t"))
8 mark4=int(input("Enter Mark4:\t"))
9
10 total=mark1+mark2+mark3+mark4
11 average=total/4
12 if mark1>=40 and mark2>=40 and mark3>=40 and mark4>=40:
13 result="Pass"
14 if average >= 75:
15 grade="Distinction"
16 elif average >= 60 and average <75:
17 grade = "First Class"
18 elif average >=50 and average < 60:
19 grade= "Second Class"
20 else:
21 grade= "Third Class"
22 else:
23 result="Re Appear"
24 grade="-------------"
25
26 print("-----------------------")
27 print (" Marks and Grade")
28 print ("--------------------")
29 print ("Mark1 :\t", mark1)
30 print ("Mark2 :\t", mark2)
31 print ("Mark3 :\t", mark3)
32 print ("Mark4 :\t", mark4)
33
34 print("Result :\t\t\t",result)
35 print("Percentage Obtained:\t ", average)
36 print("Grade:\t\t\t",grade)

The example shows mark list processing using if-elif-else. Marks for four
subjects are read from the user from lines 5 to 8. The total and average of the
marks are calculated. If marks in all the subjects are greater than or equal to 40,
then the result will be Pass. If Pass, then grade will be calculated. If Fail, there is
no grade and the result will be printed as “Re Appear”.
Output
Enter Mark1: 67
Enter Mark2: 81
Enter Mark3: 64
Enter Mark4: 70
-----------------------
Marks and Grade
-----------------------
Mark1 : 67
Mark2 : 81
Mark3 : 64
Mark4 : 70
Result : Pass
Percentage Obtained: 70.5
Grade: First Class
Tip: switch..case is not supported in Python. But it can be implemented using the
elif statement. Similarly, there is no ternary or conditional operator(?:) in Python.

Looping Structure or Repetition Structure

If the set of statements are executed repeatedly, it is known as Looping


Structure. Instead of writing the same sequence of statements over and over, it is
written once and then placed in a structure that makes the computer repeat it as
many times as necessary. This can be done with a repetition structure, which is
more commonly known as a loop. The set of statements that are executed
repeatedly is called as a loop body. The looping structure is classified into two
broad categories.
a. Entry controlled Statements and
b. Exit controlled Statements

In entry controlled statements, the set of statements are allowed to execute only
after testing the conditional expression. If the conditional expression results true,
the looping statements are executed.
In exit controlled statements, the decision to repeat the set of statements is
decided only at the end of the looping statements. The conditional expression to
continue the loop is tested, and if it results true, then the set of statements are
repeated. In exit controlled loop, the body of the loop will be executed at least
once if the conditional expression results false initially.

They are further classified into


a. Condition controlled statements and
b. Count controlled statements
A condition-controlled loop uses a true/false condition to control the number
of times that it repeats. A count-controlled loop repeats the block for a specific
number of times. In Python, the ‘while’ statement is used to write a condition-
controlled loop and the ‘for’ statement is used to write a count-controlled loop.
while Loop

‘while’ loop comes under entry controlled loop. It first tests the condition and
then continues with iteration. The test is done at the beginning of the loop. The
loop has two parts
a. a condition that is tested for a true or false value and
b. a statement or set of statements that is repeated as long as the condition is
true.
Syntax:
while conditional_expression:
Statement
Statement
Statement
statement-in-sequence

The first line refers to the while clause header. It begins with the keyword ‘while’,
followed by a boolean conditional expression that will be evaluated as either true
or false. When the while loop executes, the conditional expression is tested. If itis
true, the statements that appear in the block following the while clause are
executed, and then the loop starts over. If the conditional expression is false, the
program exits the loop and continues with statement-in-sequence, the next
statement of the program.

Fig Flowchart for the while statement


The while clause requires a loop control variable and it decides whether the
looping statements are continued or not. In a count controlled loop, it should be
initialized before starting the loop, and inside the loop it should be incremented
or decremented.
Example
Program : Implementation of while statement

1 #Print the numbers from 11 to 20


2 #uses while loop
3
4 i=11
5 while i<=20:
6 print(i)
7 i += 1
8
9 print("Next Statement in Sequence")

The above program shows condition controlled while loop. It has three parts.
First is the loop control variable ‘i’. It should be initialized before the starting of
the loop with the starting value 11. The second is the while clause header. It
checks whether the loop controlled variable reaches 21. If ‘i’ is less than or equal
to 20, the loop body will be executed. The third one is incrementing the loop
control variable ‘i'. By changing the value of ‘i’ loop is made to continue or exit.
Inside the loop body, the executable statements are introduced.
Output
11
12
13
14
15
16
17
18
19
20
Next Statement in Sequence
>>>

When ‘i' reaches 21, the control jumps to the while clause header and checks
the condition. Now the condition is false, so the control moves to the next
statement in sequence. The only way to exit from the loop is to make the
conditional expression false.
In a condition controlled loop, the loop control variable is not incremented or
decremented inside the loop body. Instead of that, it should be modified to apply
the conditional expression. Program 4.6 shows a condition controlled loop. The
object ‘option’ is used as a condition controlled variable. Every time the
conditional expression checks whether it is equal to ‘y’. If it is so, the looping
statements are executed and the loop is continued. Otherwise, control exits from
the loop and the next statement will be executed. If the option flag is not equal to
‘y’, the contents of the list will be displayed.
Example
Program : while statement with conditional flag

1 #Create a list dynamically and display it


2 numberList=list()
3 option='y' # initialize the flag
4
5 while option == 'y' : #condition controlled flag
6 no=int(input("Enter any number:\t"))
7 [Link](no)
8 print(" ")
9 option=input("Want to read again ?Enter 'y' to read:\t")
10
11 print("Number List Created Successfully")
print ("The list is:",numberList)

Output
Enter any number: 45

Want to read again? Enter 'y' to read: y


Enter any number: 200

Want to read again? Enter 'y' to read: y


Enter any number: 12

Want to read again? Enter 'y' to read: y


Enter any number: 99

Want to read again? Enter 'y' to read: n


Number List Created Successfully
The list is: [45, 200, 12, 99]
>>>
The statement block of while loop may have a single statement also. For example,
only a print statement is required to display the list’s contents one by one. It is
mentioned below.
numberList=[23,56,10,90]
while numberList: print([Link]())

Output
23
56
10
90
for loop

In programming languages like C, Java etc, the for loop follows the traditional
format. It includes the initialization, checking for conditional expression to
continue the loop and modifying the value of loop control variable in for clause
header. But in Python the for loop acts like a ‘for each’ loop as in other scripting
languages.
Syntax
for iteration_object in sequence:
suite/block of statements/loop body
next-statement

The for clause header retrieves each item in the sequence into an iteration
object (variable) and executes the loop body until there is no element in the
sequence. The for loop is applied only to sequence types of objects. The iteration
is done with individual items in the sequence or with the index of the sequence.

Fig Flowchart of for loop

Example

Program : Implementation of for statement

1 #print the elements of the list


2 numberList=[23,56,10,90]
3 for nlist in numberList:
4 print(nlist)
5 print("Elements of List is printed\n")
6
7 #print the elements of the string
8 for item in "Compuetr":
9 print(item)
10 print("Items in String is printed")

The program displays the elements of the sequence type data (List and String)
using a for loop. The items from the numberList are retrieved one by one,
assigned it one by one, and assigned to iterator object nlist. Then it is displayed.
Output
23
56
10
90
Elements of List is printed
C
o
m
p
u
e
t
r
Items in String is printed
>>>
Instead of iterating over individual items, indices can also be used for iteration
and it is done with range() built-in function. The range() function takes only the
continuous values from starting and end value-1 with step. It is done with the help
of range() built-in function.
Syntax
range(start,end,step)
where:
start: indicates initial value
end : indicates last value
step : indicates increment value and it is optional.

All the values in between the start and end-1 value will be generated. The
default step value is 1. If the step value is anything other than 1, it will be added
to the start value to obtain the next value.
Example: The below code prints the number from 10 to 14 using range()
function.
>>> for a in range(10,15): print(a)

10
11
12
13
14
>>>
Example 2: The introduction of step value modifies the value assigned to the
iteration object.

>>> for b in range(10,20,2): print(b)

10
12
14
16
18
>>>

Example 3: The step value may be a negative value. Negative step value
decrements the start up to end value every time.
>>> for c in range(20,10,-2):print(c)

20
18
16
14
12
>>>

The loop with indices is usually combined with the range() function with the
len() function to make the code easier.
Example
Program : for statement with range() function

1 #print the elements of the list using range()


2 numberList=[23,56,10,90]
3 for i in range(0,len(numberList)):
4 print(i,"th element is:",numberList[i])
5 print("Elements of List is printed\n")

In the above program the range() function generates the index of the list from
0 to the length of the sequence minus 1. Then to retrieve the elements from
numberList, the subscription operator[ ] with index i is used.([i])
Output
0 th element is: 23
1 th element is: 56
2 th element is: 10
3 th element is: 90
Elements of List is printed
>>>
Loop Statements with else clause

In Python, while and for loops can also be used with the else clause. The else
clause is executed if the conditional expression is false in the while loop. The else
clause will be executed only when a break statement does not terminate the
loop. The normal exit from the loop executes the else clause, whereas the pre
matured exit does not execute the else clause.
Program: while with else

1 #Implementation of While with elseclause


2 i=0
3 while i <=3:
4 print (i)
5 i +=1
6 else:
7 print ("else part of while")
8 print("Next statement")

In program the loop is terminated after printing all the specified values of ‘i’. That
is the loop follows normal exit. So the statements in else block is continued after
it.
Output
0
1
2
3
else part of while
Next statement
>>>
Program:else clause implementation with while

1 #Implementation of While with else clause


2 i=0
3 while i <=3:
4 print (i)
5 break
6 i +=1
7 else:
8 print ("else part of while")
9 print("Next statement")

Program is same as that of program 4.9 with only one difference. It is the
introduction of break statement after printing ‘i' value. The break statement in
line number 5 causes premature exit from the while loop. So the else block
statement is not executed.
Output
0
Next statement
>>>

Loop Control Statements


The loop control statements change the execution of statements inside the loop
body. There are three loop control statements in Python. They are
a. break statement
b. continue statement
c. pass statement
break statement

The break statement in Python terminates the current loop and continues the
execution from the next statement in sequence with the program. It is used to
come out from the loop completely. The break statement can be used in
both while and for loops.
Syntax:
Break
Program : use of break statement

1 #Read a string and print the characters till the first vowel is found
2 string1=input("Enter any String:\t")
3 for s in range(0,len(string1)):
4 if string1[s] == 'a' or string1[s]=='e' or string1[s]=='i' or \
5 string1[s]=='o' or string1[s]=='u':
6 break
7 print(string1[s])
8 print("First vowel found in position", s)

Line number 2 reads a sentence from the user. Using the for loop with range()
and len() function, the index is extracted and assigned to the object ‘s’. Then the
character which is specified by the position’s’ in string1 is checked for vowel. If
it is not a vowel (a,e,i,o,u), it will be printed. If it is a vowel, the break statement
is executed which moves the control out of the loop and the loop is terminated.
The program uses a break statement to completely exit out of the loop when the
vowel is found.
Output
Enter any String: Python is a interpreted language
P
y
t
h
First vowel found in position 4
>>>
continue statement

The continue statement returns the control to the beginning of the loop clause
header. The continue skips the remaining statements in the current iteration of the
loop and moves the control back to the top of the loop. The continue statement
can be used in both while and for loops.

Syntax:
Continue
Program : use of continue statement

1 #Read a string and print all the characters except vowels


2 # uses continue statement to skip vowels
3 string1=input("Enter any String:\t")
4 for s in range(0,len(string1)):
5 if string1[s] == 'a' or string1[s]=='e' or string1[s]=='i'\
6 or string1[s]=='o' or string1[s]=='u':
7 continue
8 print(string1[s])
9
10 print("All the consonants are printed")

Output of the above program


Enter any String: Computer
C
m
p
t
r
All the consonants are printed
>>>
In Program, if any vowel character from (a,e,i,o,u) is found, it is skipped using
continue statement. But the successive characters are tested for vowel and prints
only the consonants

pass statement

The pass statement is called as a do-nothing statement. It does not perform any
activity. The pass statement is used when a statement is required syntactically but
does not execute any code. This is useful to test the flow of the statement block
for example, the function definition.
Program: use of pass statement

1 #use of pass inside while does not perform anything


2 i=0
3 while i<=10:
4 pass
5 i +=1
6 print("The value of i after loop is:",i)

The pass statement inside the loop does not perform anything forms a do-nothing
loop. Instead, the loop control variable ‘i’ is incremented and tested for every
time until it reaches 11. If it reaches 11, the conditional expression is made false,
and the next statement's sequence will be executed.
Output

The value of i after loop is: 11


>>>
Nested Loops
One loop may be introduced inside another loop. It is called a nested loop. It is
possible with while and/or for loop.
Program: use of nested for loops

1 #printing patterns with *


2
3 rows=int(input("Enetr number of rows:\t"))
4 for i in range(1,rows+1):
5 for j in range(0,i):
6 print('*',end=' ')
7 print("\n")

The program prints ‘*’ for the number of rows times. For that, a nested for loop
is used. The outer loop with loop control variable ‘i’ indicates row,s and the inner
loop with loop control variable ‘j’ specifies columns.
Output
Enetr number of rows: 4
*
* *
* * *
* * * *
>>>
Infinite Loops

If a loop does not stop a way, it is called an infinite loop. An infinite loop
continues to repeat until the program is interrupted. Infinite loops usually occur
when the programmer forgets to write code inside the loop that makes the test
condition false. In most circumstances, you must avoid writing infinite loops.
Example
Program: infinite loop
1 #infinite Loop
2 #Print the numbers from 10 to 20
3 i=10
4 while i!=-1:
5 print i
6 i +=1
7 print "Nicely print the numbers"
Output
math module
The math module is a collection of mathematical functions. These include
trigonometric functions, representation functions, logarithmic functions, angle
conversion functions, etc. In addition, two mathematical constants pi and e are
also defined in this module.
[Link] gives the value 3.141592653589793
math.e gives Euler’s number. It is the base of natural logarithm. Its value is
2.718281828459045.

Methods Description Example


radians(degrees) Converts degrees >>> import math
into radians >>> [Link](45)
0.7853981633974483
degrees(value in Converts radians >>> import math
radians) into degrees >>>
[Link](0.785)
44.97718691776962
Trigonometric Requires angle in >>> import math
functions:sin(), cos() radians as its >>>
& tan() argument. [Link](0.5235987755
982988)
0.49999999999999994

log(number) returns the natural >>> import math


logarithm of a >>>[Link](10)
given number 2.302585092994046
log10(number) returns the base-10 >>> import math
logarithm of the >>>math.log10(10)
given number. 1.0

exp(num) Returns >>> import math


exp(x) gives e**x. >>>[Link](10)
22026.465794806718

pow(num1, num2) receives two float >>> import math


arguments, raises >>> [Link](2,4)
the first to the 16.0
second and returns
the result
sqrt(num) returns the square >>> import math
root of a given >>> [Link](100)
number. 10.0
floor(float-num) returns the largest >>> import math
integer less than or >>> [Link](4.5867)
equal to the given 5
number.
ceil(float-num) given number to >>> import math
the smallest >>> [Link](4.5687)
integer, greater 4
than or equal to
the given floating
point number.

You might also like