0% found this document useful (0 votes)
3 views38 pages

Python Notes -Unit -1

python

Uploaded by

iceis123cold
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)
3 views38 pages

Python Notes -Unit -1

python

Uploaded by

iceis123cold
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
You are on page 1/ 38

IMS Engineering College

NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.


Tel: (0120) 4940000
Department of Computer Science & Engineering

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,

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 many interpreters available freely to run Python scripts like IDLE (Integrated
Development Environment) which is installed when you install the python software from
http://python.org/downloads/

Why the Name Python?

There is a fact behind choosing the name Python. Guido van Rossum was reading the script of a
popular BBC comedy series "Monty Python's Flying Circus". It was late on-air 1970s.

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)
2
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

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

3
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

The formation of python syntax is simple and straight forward which also makes it popular.

Key features of Python

1. Easy To Learn and Readable Language

It is extremely easy to learn and code in Python and the indentation used instead of curly braces in
Python makes it very easy to read Python code.

2. Interpreted Language

Python is an interpreted language (an interpreted language is a programming language that is


generally interpreted, without compiling a program into machine instructions. It is one where the
instructions are not directly executed by the target machine, but instead, read and executed by some
other program known as the interpreter) and an IDLE (Interactive Development Environment) is
packaged along with Python. It is nothing but an interpreter which follows the REPL (Read
Evaluate Print Loop) structure just like in Node.js. IDLE executes and displays the output of one
line of Python code at a time. Hence, it displays errors when we are running a line of Python code
and displays the entire stack trace for the error.

3. Dynamically Typed Language

Python is a dynamically typed language. In other words, in Python, we do not need to declare the
data types of the variables which we define. It is the job of the Python interpreter to determine the
data types of the variables at runtime based on the types of the parts of the expression. Though it
makes coding easier for programmers, this property might create runtime errors.

4
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

4. Open Source And Free

Python is an open-source programming language and one can download it for free from Python’s
official website. The community of Python users is constantly contributing to the code of Python in
order to improve it.

5. Large Standard Library

One of the very important features because of which Python is so famous in today’s times is the
huge standard library it offers to its users. The standard library of Python is extremely large with a
diverse set of packages and modules like itertools, functools, operator, and many more with
common and important functionalities in them

6. High-Level Language

A high-level language (HLL) 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
said to be high-level since they are very close to human languages and far away from machine
languages.

Unlike C, Python is a high-level language. We can easily understand Python and it is closer to the
user than middle-level languages like C. In Python, we do not need to remember system
architecture or manage the memory.

7. Object Oriented Programming Language

Python supports various programming paradigms like structured programming, functional


programming, and object-oriented programming.

5
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

However, the most important fact is that the Object-Oriented approach of Python allows its users to
implement the concepts of Encapsulation, Inheritance, Polymorphism, etc. which is extremely
important for the coding done in most Software Industries as objects map to entities in real-world
and lot of real-world problems can be solved using the Object-Oriented Approach.

8. Large Community Support

With one of the biggest communities on StackOverflow and Meetup, Python has gained popularity
over the years. If we need any kind of help related to Python, the huge community is always there
to answer our queries. A lot of questions about Python have already been answered on these sites
and Python users can reference them as per requirement.

9. Platform Independent

Platform independence is yet another amazing feature of Python. In other words, it means that if we
write a program in Python, it can run on a variety of platforms, for instance, Windows, Mac, Linux,
etc. We do not have to write separate Python code for different platforms.

11. Graphical User Interface (GUI) Support

Yet another interesting feature of Python is the fact that we can use it to create GUI (Graphical User
Interfaces). We can use Tkinter, PyQt, wxPython, or Pyside for doing the same. Python also
features a large number of GUI frameworks available for it and various other cross-platform
solutions. Python binds to platform-specific technologies.

6
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

Application Areas 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.

Here, we are specifying application areas where Python can be applied.

7
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

Programming cycle for Python

The programming cycle for Python is a stage-by-stage method for developing systematic software.

Problem description is the first step in the development process, during which developers define the

project’s needs, limitations, and goals. Their algorithm, data structures, and technological requirements

are needed to address the challenge. They are created in depth at the planning stage by developers.

The Programming Cycle For Python

The Python programming cycle can assist developers in producing high-quality, dependable, and

scalable solutions. It is a recognized method of software development that is applied in several

different industries. The programming cycle has shown to be successful in producing reliable software

solutions. In short:

1. The programming cycle for Python is far shorter than the cycle for conventional programming.

2. Compile and link operations are not necessary in Python.

3. During runtime, Python programs only load modules and use the objects. they do have. As a result,

Python scripts run as soon as you do modifications.

4. It is even possible to change and reload portions of a current application. It is possible without

halting it altogether in situations where you can use dynamic module reloading.

8
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

Getting started with Python Programming –

Python is a lot easier to code and learn. Python programs can be written on any plain text editor like
notepad, notepad++, or anything of that sort.
We can also use an online IDE for writing Python codes or can even install one on their system to make
it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor,
debugger, compiler, etc.
To begin with, writing Python Codes and performing various intriguing and useful operations, one must
have Python installed on their System.

Generally, there are two ways to run a Python program.


 Using IDEs: We can use various IDEs(Pycharm, Jupyter Notebook, etc.) which can be used
to run Python programs.
 Using Command-Line: We can also use command line options to run a Python program.

Python IDE:

Introduction to IDEs and Code Editors

9
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

An integrated development environment (IDE) is a program dedicated to software development. As


the name implies, IDEs integrate several tools specifically designed for software development.
These tools usually include:

 An editor designed to handle code (with, for example, syntax highlighting and auto-
completion)
 Build, execution, and debugging tools
 Some form of source control

Most IDEs support many different programming languages and contain many more features. They
can, therefore, be large and take time to download and install. You may also need advanced
knowledge to use them properly

General Editors and IDEs with Python Support

Visual Studio Code

Category: Code Editor


Website: https://code.visualstudio.com/
Eclipse + PyDev
Category: IDE
Website: www.eclipse.org

Sublime Text
Category: Code Editor
Website: http://www.sublimetext.com

Vi / Vim
Category: Code Editor
Website: https://www.vim.org/

Python-Specific Editors and IDEs

PyCharm
Category: IDE
Website: https://www.jetbrains.com/pycharm/

Spyder
Category: IDE
Website: https://www.spyder-ide.org/
10
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

Thonny
Category: IDE
Website: http://thonny.org/

Installation on Windows
Visit the link https://www.python.org to download the latest release of Python. In this process, we
will install Python 3.11.3 on our Windows operating system. When we click on the above link, it
will bring us the following page.

Step 1: Select the Python's version to download.

Click on the download button to download the exe file of Python.

Step 2 : Click on the Install Now


11
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

To verify whether the python is installed or not in our system, we have to do the following.
o Go to "Start" button, and search " cmd ".
o Then type, " python - - version ".
o If python is successfully installed, then we can see the version of the python installed.
o If not installed, then it will print the error as " 'python' is not recognized as an internal or
external command, operable program or batch file. "

How is Python an interpreted language?

Python is an interpreted language, which means the source code of a Python program is
converted into bytecode that is then executed by the Python virtual machine. Python is
different from major compiled languages, such as C and C + +, as Python code is not
required to be built and linked like code for these languages.

Modes of Python Programming:

12
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

Python Interpreter is a program that reads and executes Python code. It uses 2 modes of Execution.

1. Interactive mode

2. Script mode

1. Interactive mode:

 Interactive Mode, as the name suggests, allows us to interact with OS.


 When we type Python statement, interpreter displays the result(s) immediately.

Advantages:

 Python, in interactive mode, is good enough to learn, experiment or explore.

 Working in interactive mode is convenient for beginners and for testing small pieces of code.

Disadvantages of interactive mode


1. The interactive mode is not suitable for large programs.
2. The interactive mode doesn’t save the statements. Once we make a program it is for that
time itself, we cannot use it in the future. In order to use it in the future, we need to retype
all the statements.
3. Editing the code written in interactive mode is a tedious task. We need to revisit all our
previous commands and if still, we could not edit we need to type everything again.

2. Script Mode

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.

 In script mode, we type python program in a file and then use interpreter to execute the
content of the file.
 Scripts can be saved to disk for future use. Python scripts have the extension .py, meaning
that the filename ends with .py

13
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

Advantages:

 It's is very suitable for long program....type all the command once and show your output at
once.
 Here we got the advantage to save our python script which is helpful for us because no
longer our python script get lost we can make changes whenever required.

Disadvantages:
1. Can be tedious when you need to run only a single or a few lines of cod.
2. You must create and save a file before executing your code.

Python Indentation
Indentation refers to the spaces at the beginning of a code line.

Where in other programming languages the indentation in code is for readability only, the indentation in
Python is very important.

Python uses indentation to indicate a block of code.

if 5 > 2:
print("Five is greater than two!")

Python Comments

Comments can be used to explain Python code.

Comments can be used to make the code more readable.

Comments can be used to prevent execution when testing code.

Creating a Comment

Comments starts with a #, and Python will ignore them:

14
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

#This is a comment
print("Hello, World!")

A comment does not have to be text that explains the code, it can also be used to prevent Python from
executing code:

#print("Hello, World!")
print("Cheers, Mate!")

Multiline Comments
Python does not really have a syntax for multiline comments.

To add a multiline comment you could insert a # for each line:

#This is a comment
#written in
#more than just one line
print("Hello, World!")

Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string
(triple quotes) in your code, and place your comment inside it:

Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

Python Keywords:
Keywords are predefined, reserved words used in Python programming that have special meanings
to the compiler.

15
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

We cannot use a keyword as a variable name, function name, or any other identifier. They are
used to define the syntax and structure of the Python language.

All the keywords except True, False and None are in lowercase and they must be written as they
are. The list of all the keywords is given below.

Python contains thirty-five keywords in the version, i.e., Python 3.8.

Python Keywords List

False Await else import pass

None Break except in raise

True Class finally is return

and Continue for lambda try

as Def from nonlocal while

assert Del global not with

async Elif if or yield

16
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

Python Variables:

Python variables are the reserved memory locations used to store values with in a Python P rogram.
This means that when we create a variable we reserve some space in the memory. Based on the data
type of a variable, Python interpreter allocates memory.

Declaring Python Variables


Python variables do not need explicit declaration to reserve memory space or we can say to create a
variable. A Python variable is created automatically when we assign a value to it.

x = 100 # Creates an integer variable

y = 1000.0 # Creates a floating point variable

name = "Python" # Creates a string variable

Identifier Naming:

Identifiers are the name given to variables, classes, methods, etc. Variables are the example of
identifiers. An Identifier is used to identify the literals used in the program.

The rules to name an identifier are given below .

o The first character of the variable must be an alphabet or underscore ( _ ).


o All the characters except the first character may be an alphabet of lower-case(a-z), upper-
case (A-Z), underscore, or digit (0-9).
o Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive; for example, my name, and MyName is not the same.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.

17
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

Declaring Variable and Assigning Values

Python does not bind us to declare a variable before using it in the application. It allows us to create
a variable at the required time.

We don't need to declare explicitly variable in Python. When we assign any value to the variable,
that variable is declared automatically.

The equal (=) operator is used to assign value to a variable.

Python Data Types


Python Data Types are used to define the type of a variable. It defines what type of data we are
going to store in a variable. The data stored in memory can be of many types. For example, a
person's age is stored as a numeric value and his or her address is stored as alphanumeric
characters.

Since everything is an object in Python programming, data types are actually classes and variables
are instances (object) of these classes.

Python has the following data types built-in by default, in these categories:

Text Type: Str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: Dict

Set Types: set, frozenset

Boolean Type: Bool

Binary Types: bytes, bytearray, memoryview

18
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

None Type: NoneType

Python type() Function?

To define the values of various data types and check their data types we use the type()
function. Consider the following examples.

Numeric Data Type in Python


The numeric data type in Python represents the data that has a numeric value. A numeric value can
be an integer, a floating number, or even a complex number. These values are defined as Python
int, Python float, and Python complex classes in Python.

19
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

 Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an integer
value can be.

 Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed
by a positive or negative integer may be appended to specify scientific notation.

 Complex Numbers – Complex number is represented by a complex class. It is specified


as (real part) + (imaginary part)j. For example – 2+3

Example:
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))

Output:
Type of a: <class 'int'>

Type of b: <class 'float'>

Type of c: <class 'complex'>

Sequence Data Type in Python


The sequence Data Type in Python is the ordered collection of similar or different data types.
Sequences allow storing of multiple values in an organized and efficient fashion. There are several
sequence types in Python –

 Python String

 Python List

 Python Tuple
20
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

String Data Type

Strings in Python are arrays of bytes representing Unicode characters. A string is a collection of one
or more characters put in a single quote, double-quote, or triple-quote.

In python there is no character data type, a character is a string of length one. It is represented by str
class.

Python strings are immutable which means when we perform an operation on strings, we always
produce a new string object of the same type, rather than mutating an existing string.

>>> type("Welcome to Python")

<class 'str'>

Python List:

Lists are just like arrays, declared in other languages which are an ordered collection of data. It is
very flexible as the items in a list do not need to be of the same type.

Lists in Python can be created by just placing the sequence inside the square brackets[].

List items are ordered, changeable, and allow duplicate values.

>>> [2023, "Python", 3.11, 5+6j, 1.23E-4]

A list in Python is an object of list class. We can check it with type() function.

>>> type([2023, "Python", 3.11, 5+6j, 1.23E-4])

<class 'list'>

As mentioned, an item in the list may be of any data type. It means that a list object can also be an
item in another list. In that case, it becomes a nested list.

>>> [['One', 'Two', 'Three'], [1,2,3], [1.0, 2.0, 3.0]]

21
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

Python Tuple Data Type:


Tuple is an ordered sequence of items same as a list. The only difference is that tuples are
immutable. Tuples once created cannot be modified.

In Python, we use the parentheses () to store items of a tuple.

>>> (2023, "Python", 3.11, 5+6j, 1.23E-4)

In Python, a tuple is an object of tuple class. We can check it with the type() function.

>>> type((2023, "Python", 3.11, 5+6j, 1.23E-4))

<class 'tuple'>

As in case of a list, an item in the tuple may also be a list, a tuple itself or an object of any other
Python class.

>>> (['One', 'Two', 'Three'], 1,2.0,3, (1.0, 2.0, 3.0))

To form a tuple, use of parentheses is optional. Data items separated by comma without any
enclosing symbols are treated as a tuple by default.

>>> 2023, "Python", 3.11, 5+6j, 1.23E-4

(2023, 'Python', 3.11, (5+6j), 0.000123)

Dictionary Data Type in Python

A dictionary in Python is an unordered collection of data values, used to store data values like a
map, unlike other Data Types that hold only a single value as an element, a Dictionary holds a key:
value pair. Key-value is provided in the dictionary to make it more optimized.

Each key-value pair in a Dictionary is separated by a colon : , whereas each key is separated by a
‘comma’.

Create a Dictionary

22
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces,
separated by ‘comma’. Values in a dictionary can be of any data type and can be duplicated,
whereas keys can’t be repeated and must be immutable.

The dictionary can also be created by the built-in function dict(). An empty dictionary can be
created by just placing it in curly braces{}.

>>> {1:'one', 2:'two', 3:'three'}

In Python, dictionary is an object of the built-in dict class. We can check it with the type() function.

>>> type({1:'one', 2:'two', 3:'three'})

<class 'dict'>

Set Data Type in Python

In Python, a Set is an unordered collection of data types that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of various
elements.

Create a Set in Python

Sets can be created by using the built-in set() function with an iterable object or a sequence by
placing the sequence inside curly braces, separated by a ‘comma’. The type of elements in a set
need not be the same, various mixed-up data type values can also be passed to the set.

Python Set is an object of built-in set class, as can be checked with the type() function.

A set can store only immutable objects such as number (int, float, complex or bool), string or
tuple. If you try to put a list or a dictionary in the set collection, Python raises a TypeError

>>> {2023, "Python", 3.11, 5+6j, 1.23E-4}

{(5+6j), 3.11, 0.000123, 'Python', 2023}

Python Boolean Data Types

23
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

Python boolean type is one of built-in data types which represents one of the two values
either True or False. Python bool() function allows us to evaluate the value of any expression and
returns either True or False based on the expression.

a = True

# display the value of a

print(a)

# display the data type of a

print(type(a))

Output:

true

<class 'bool'>

Operators and operands


 Operators are special symbols that represent computations like addition and multiplication.
 The values the operator is applied to are called operands.
 Expression: An Expression is a combination of operators and operands that computes a
value when executed by the Python interpreter

The operator in Python are classified as follow:

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operator
5. Assignment Operators
6. Membership Operators
7. Identity Operators

Arithmetic Operators:

24
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

These operators are used to perform operations such as addition, subtraction, multiplication,
division and modulo division. For example, x=7, and y=3.

Operator Meaning Example


+ Addition-Used to perform arithmetic addition x+y, results in 10
- Subtraction-Used to perform arithmetic subtraction x-y, results in 4
* Multiplication-Used to perform multiplication x*y, results in 21
/ Division-Used to perform division x/y , results in 2
% Modulus-Used to perform modulus operation (remainder) x%y, results in 1
// Used to perform floor division (floor value) x//y, results in 2
** Exponent- Used to raise operand on left to the power of x**y, 343
operand on right

Comparison (Relational) Operators

These operators are used to compare value. The operators can either return True or False
according to the condition. The table with following values for x=7 and y=3

Operator Meaning Example


> Greater Than-Returns True if the left operand is greater than x>y, results in True
the right, otherwise returns False
< Less Than-Returns True if the left operand is less than the X<y, results in False
right, otherwise returns False
== Equal to-Returns True if both are equal, otherwise False x==y, returns False
!= Not Equal to- Returns True if both are not equal, otherwise x!=y, return True
False
>= Greater than or Equal- Returns True if the left operand is x>y, returns True
greater than or equal to the right, otherwise returns False
<= Less than or Equal- Returns True if the left operand is Less X<y, returns False
than or equal to the right, otherwise returns False

Example Program: relp.py

Source Code Output

25
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

x=input("Enter value of x ") Enter value of x 7


y=input("Enter value of y ") Enter value of y 3
print " "
print " Greater than is:",(x>y) Greater than is: True
print " Less Than is:",(x<y) Less Than is: False
print " Equality is :",(x==y) Equality is : False
print " Not equal is:",(x!=y) Not equal is: True
print " Greater than or equal is:",(x>=y) Greater than or equal is: True
print " Less than or equal is:",(x<=y) Less than or equal is: False
print " "

26
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

Bitwise Operators
Bitwise operators act on operands as if they were string of binary digits. The operators operate
bit by bit. For example, x=2 (binary value is 10) and y=7 (Binary value is 111). The binary
equivalent of the decimal values of x and y will be 10 and 111 respectively.

Operator Meaning Example


& Bitwise AND X&y=0
x=010
y=111
x&y= 010 ( 2)
| Bitwise OR x|y=7
x=010
y=111
x|y=111 (7)
~ Bitwise Not ~x is ,-3
^ Exclusive OR (XOR) X^y=5
x=010
y=111
x|y=101 (5)
>> Shift Right (operand >>no. of bit positions) x>>1, results 1
<< Shift Left (operand <<no. of bit positions) X<<2, 1000 (8)

Example Program: bitop.py

Source Code Out put


x=input("Enter value of x :") Enter value of x :2
y=input("Enter value of y :") Enter value of y :7
print "-----Bitwise Operations ------- " -----Bitwise Operations--------
print " AND (&) is:",(x&y) AND (&) is: 2
print " OR (|) is:",(x|y) OR (|) is: 7
print " XOR (^) is:",(x^y) XOR (^) is: 5
print " Not (~) is:",(~x) Not (~) is: -3
print " Shift Right(>>) is:",(x>>1) Shift Right(>>) is: 1
print " Shift Left (<<)is:",(x<<2) Shift Left (<<)is: 8
print " "

Logical Operator:
27
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

There are three logical operators: and, or, and not. The semantics (meaning) of these
operators is similar to their meaning in English. For example, x > 0 and x < 10 is true only if x is
greater than 0 and less than 10. n % 2 == 0 or n % 3 == 0 is true if either (or both) of the
conditions is true, that is, if the number is divisible by 2 or 3. Finally, the not operator negates a
boolean expression, so not(x > y) is true if (x > y) is false, that is, if x is less than or equal to y.

28
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

Operator Meaning Example


And True if both the operands are x and y
True
Or True, if either of the operands x or y
is True
Not True if operand false not x

Example Program: logop.py

Source Code Out Put


x=True x and y is : False
y=False x or y is : True
print " x and y is :",x and y not x is: False
print " x or y is :",x or y
print " not x is:",not x

Assignment Operator

Assignment operator is used to assign values to the variable. For example, x=5 is simple
assignment operator, that assigns value 5 to the to the variable x.
There are various compound operators in python like a+=5, which adds value 5 to the variable
and later assigns it to variable
a. This expressions is equivalent to a=a+5.
b. The same assignment operator can be applied to all expressions that contain arithmetic
operators such as, *=, /=, -=, **=,%= etc.

x=4
x+=5
>>> x
print “The value of x is:”, x
>>> The value of x 9

Membership Operators

These operators are used to test whether a value or operand is there in the sequence such as list,
string, set, or dictionary. There are two membership operators in python: in and not in. In the

29
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science & Engineering

dictionary we can use to find the presence of the key, not the value.

Operator Meaning Example


In True if value or operand is 5 in x
present in the sequence
not in True if value or operand is not 5 not in x
present in the sequence

Example Program:

Source Code Output


#membership operator: in and not in ('H in x', True)
x="Hello Python" # string ('hello in x', False)

30
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.

Tel: (0120) 4940000

Department of Computer Science & Engineering

y={1:'a',2:'n',3:'t'} #dictionary ('1 in y', True)


print ("H in x",'H' in x) ('a in y', False)
print ("hello in x","hello" in x)
print ("1 in y",1 in y) # 1 key key in dictionary
print ("a in y",'a' in y) #a is value in dictionary

Identity Operators

These are used to check if two values (variable) are located on the same part of the memory. If the x is a
variable contain some value, it is assigned to variable y. Now both variables are pointing (referring) to
the same location on the memory as shown in the example program.

Operator Meaning Example


Is True if the operands are X=5
identical ( refer to the same Y=X
memory) X is Y , returns True
is not True if the operands are not X=5 #int
identical ( refer to the same Y=5.0 # float
memory) X is not Y, returns True

Example Program:

Source Code Output


#indetity operator program ('x is y', False)
x=[1,2,3] #list ('x is z', True)
y=[1,2,3] #list
z=x
print ("x is y", x is y) # x and y are different
Objects
print ("x is z", x is z) # x and z are refering to
same object

31
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.

Tel: (0120) 4940000

Department of Computer Science & Engineering

Python Input, Output:

Python provides numerous built-in functions that are readily available to us at the Python prompt.

Some of the functions like input() and print() are widely used for standard input and output operations
respectively

Python Output Using print() function

We use the print() function to output data to the standard output device (screen).

The simplest way to produce output is using the print() function where we can pass zero or more
expressions separated by commas.

This function converts the expressions we pass into a string before writing to the screen.

Ex:

a=5

print('The value of a is', a)

Output

The value of a is 5

Syntax: print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)

Parameters:
value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : Optional) Specify how to separate the objects, if there is more than one.Default :’
‘end=’end’ : (Optional) Specify what to print at the end. Default : ‘\n’
file : (Optional) An object with a write method. Default : sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered
(False).Default: False

32
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.

Tel: (0120) 4940000

Department of Computer Science & Engineering

Returns: It returns output to the screen.

Example:

print(1, 2, 3, 4)

print(1, 2, 3, 4, sep='*')

print(1, 2, 3, 4, sep='#', end='&')

Output

1234

1*2*3*4

1#2#3#4&

Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by using
the str.format() method. This method is visible to any string object.

>>> x = 5; y = 10

>>> print('The value of x is {} and y is {}'.format(x,y))

The value of x is 5 and y is 10

Here, the curly braces {} are used as placeholders. We can specify the order in which they are printed
by using numbers (tuple index).

print('I love {0} and {1}'.format('bread','butter'))

print('I love {1} and {0}'.format('bread','butter'))

Output

I love bread and butter

I love butter and bread

We can even use keyword arguments to format the string.


33
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.

Tel: (0120) 4940000

Department of Computer Science & Engineering

>>> print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name =

'John'))

Hello John, Goodmorning

We can also format strings like the old sprintf() style used in C programming language . We use
the % operator to accomplish this.

>>> x = 12.3456789

>>> print('The value of x is %3.2f' %x)

The value of x is 12.35

>>> print('The value of x is %3.4f' %x)

The value of x is 12.3457

Python Input:
To allow flexibility, we might want to take the input from the user. In Python, we have
the input() function to allow this. The syntax for input() is:

**Python 2.7 uses the raw_input() method

input([prompt])

where prompt is the string we wish to display on the screen. It is optional.

>>> num = input('Enter a number: ')

Enter a number: 10

>>> num

'10'

Here, we can see that the entered value 10 is a string, not a number. To convert this into a number we can
use int() or float() functions.

34
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.

Tel: (0120) 4940000

Department of Computer Science & Engineering

>>> int('10')

10

>>> float('10')

10.0

How the input function works in Python :

When input() function executes program flow will be stopped until the user has given an input.

The text or message display on the output screen to ask a user to enter input value is optional i.e. the
prompt, will be printed on the screen is optional.

Whatever you enter as input, input function convert it into a string. if you enter an integer value
still input() function convert it into a string. You need to explicitly convert it into an integer in your code
using typecasting.

Typecasting Example:

num1 = int(input())

num2 = int(input())

# printing the sum in integer

print(num1 + num2)

Taking multiple inputs from user in Python:

In C++/C we can take multiple inputs in one line using scanf but in Python we can take multiple values or
inputs in one line by two methods.

Using split() method

Using List comprehension

Using split() method :

35
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.

Tel: (0120) 4940000

Department of Computer Science & Engineering

This function helps in getting a multiple inputs from user . It breaks the given input by the specified
separator. If separator is not provided then any white space is a separator. Generally, user use
a split() method to split a Python string but one can used it in taking multiple input.

Syntax :

input().split(separator, maxsplit)

Example :

1. Taking two inputs at a time

x, y = input("Enter a two value: ").split()

print("Number of boys: ", x)

print("Number of girls: ", y)

3. taking three inputs at a time

x, y, z = input("Enter a three value: ").split()

print("Total number of students: ", x)

print("Number of boys is : ", y)

print("Number of girls is : ", z)

4. taking two inputs at a time

a, b = input("Enter a two value: ").split()

print("First number is {} and second number is {}".format(a, b))

5. Taking multiple inputs at a time and type casting using list() function

x = list(map(int, input("Enter a multiple value: ").split()))

print("List of students: ", x)

Output:

36
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.

Tel: (0120) 4940000

Department of Computer Science & Engineering

Using List comprehension :

List comprehension is an elegant way to define and create list in Python. We can create lists just like
mathematical statements in one line only. It is also used in getting multiple inputs from a user.

1. Taking two input at a time

x, y = [int(x) for x in input("Enter two value: ").split()]

print("First Number is: ", x)

print("Second Number is: ", y)

print()

2. Taking three input at a time

x, y, z = [int(x) for x in input("Enter three value: ").split()]

print("First Number is: ", x)

print("Second Number is: ", y)

print("Third Number is: ", z)

print()

37
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.

Tel: (0120) 4940000

Department of Computer Science & Engineering

3. Taking two inputs at a time

x, y = [int(x) for x in input("Enter two value: ").split()]

print("First number is {} and second number is {}".format(x, y))

print()

4. Taking multiple inputs at a time

x = [int(x) for x in input("Enter multiple value: ").split()]

print("Number of list is: ", x)

Output:

Note : The above examples take input separated by spaces. In case we wish to take input separated by
comma (, ), we can use following:

# taking multiple inputs at a time separated by comma

x = [int(x) for x in input("Enter multiple value: ").split(",")]

print("Number of list is: ", x)

38

You might also like