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

Chapter - 1 Introduction, Data Types and Operators

The document discusses features and installation of Python programming language. It covers various data types in Python like variables, inputs, comments, reserved words and operators like arithmetic, comparison, logical etc. It provides an overview of topics that will be covered in the chapter including installation of Python, working with variables and data types, and using operators to perform computations and logical statements.

Uploaded by

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

Chapter - 1 Introduction, Data Types and Operators

The document discusses features and installation of Python programming language. It covers various data types in Python like variables, inputs, comments, reserved words and operators like arithmetic, comparison, logical etc. It provides an overview of topics that will be covered in the chapter including installation of Python, working with variables and data types, and using operators to perform computations and logical statements.

Uploaded by

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

TABLE OF CONTENTS

Chapter - 1 Introduction, Data Types and Operators


(1 1) to (1 -24)
1.1 Features of Python Programming. ... 1 -2

1.2 Installation and Working with Python. ...1-3

1.2.1 Modes of Working in Python.. 1-6

1.3 Variables.... .1-9

1.4 Data Types in Python... 1-9

1.5 Input Operations. 1-13

... 1 - 15
1.6 Comments....

1.7 Reserved Words 1 16


1.8 Indentation.. 1-16

1.9 Perform Computations and Create Logical


Statements using Python's Operators. 1-16

1.9.1 Arithmetic Operators . . *****.***°*


... 1 - 16

1.9.2 Comparison Operators... ************


..1-17

1.9.3 Logical Operators... ********** . 1 18

1.9.4 Bitwise Operators. . 1-18

1.9.5 Assignment Operators.. ...1-19

1.9.6 Membership Operators.. ...1-21

...1-22
1.9.7 Identity Operators.. °°°**°°*.

1.9.8 Modulus Operator.. ...1-23

1.9.9 List, Tuple and String Operators.. . .1-24

Chapter 2 Python Decision Making and Loop (2 1) to (2 56)

2.1 Conditional Statements.. . . 2-2

..2-2
2.1.1 If Statement..
....2-3
2.1.2 If-else.
2 -4
2.1.3 Nested if.

()
JENIL THAKKAR
Introduction, Data Types
1 and Operators

Syllabus
Introduction, Data Types and Operators:lnstallation and working with Python, Variables
anddata types in python, Perform commputations and create logical statements using Python's
operators: Arithmetic, Assignment, Comparison, Logical, Membership, Identity, Bitwise
operators, list, tuple and string operations.

Contents
1.1 Features of Python Programming
1.2 Installation and Working with Python

1.3 Variables
1.4 Data Types in Python

1.5 Input Operations


1.6 Comments

1.7 Reserved Words


1.8 Indentation
1.9 Perform Computations and Create Logical Statements using Python's Operators

(1-1)
JENIL THAKKAR
Python Programming 1-2 Introduction, Data Types and Operators

1.1 Features of Python Programming


Python is a powerful programming language. Following are features of python :
1. Python is free and open source programming language. The software can be
downloaded and used freely.
2. It high level programming language.
3. It is simple and easy to learn.
4. It is portable. That means python programs can be executed on various platforms
without altering them.
5. The Python programs do not require compilation, rather they are interpreted.

Internally, Python converts the source code into an intermediate form called
bytecodes and then translates this into the native language of your computer and
then runs it.
6. It is an object oriented programming language.
7.
7. It can be embedded within your C or Ct+ programs.
8. It is rich set of functionality available in its huge standard library.

9. Python has a powerful set of built-in data types and easy-to-use control
constructs.

10. It has rich and supportive community to help the developer while creating new

applications.
11. Using few lines of code many useful applications can be developed using Python.
Uses of Python in industry

Top companies are using Python as their business application development. Even
the Central Intelligence Agency (CIA) is using Python to maintain their websites.

Google's first search engine was written in Python. It was developed in the late
90s.
Facebook uses the Python language in their production engineering.
.NASA uses workflow automation tool which is written in Python.
. Nokia which is a popular telecommunication company who uses Python for its

platform such as S60.


The entire stack of Dropbox was written in Python.
Quora is a popular social commenting websites which is also written in Python.
Instagram is another website which uses Python for its front-end.
YouTube also uses scripted Python for their websites.

TECHNICAL PUBLICATIONS- An up thrust for knowledge


JENIL THAKKAR
Python Programming 1-3 Introduction, Data Types and Operators

1.2 Installation and Working with Python


First, download the latest version of Python from the official website. I have
downloaded Python 3.7 version. For that purpose open the web site
https://www.python.org

Duthog

Now Select the file based on architecture of your PC. For Windows it can be 32 bit or
64 bit. If it is 32 bit then select the file as shown in the following screen shot
wwwwoesseenwe eee

Files

***fmn*.ooos.*. oo.*..***************

w******* ** wwwwwwwww.e

wwwww www ammwwwwi

TECHNICAL PUBLICATIONS- An up thrust for knowledge


JENIL THAKKAR
Python Programming
1-4
Introduction, Data Types and Op
The executable file Python 3.7.3.exe will get downloaded on your PCc N Operators
click this executable file to install Python. For 64-bit architecture,
ecture, select Wind.iow double
select Windows:
executable installer.
X86-64
Then following screen will appear. Just check the Add path checkboxand eli.
nstall
Now. The illustrative screenshot
will help you.

Install Python 3.7.3 (32-bit)


Seiect nstaN Now to insta ythan eith defauit sertings. er choose

staNW
sesttardekariApARaidcaiPrgPYPAaPAan372

**
mize iristaaatiorn Step 2: (Kk t»
wwwwwawewwem

Ste Ceckths
python
windows ****************

The installation will progress.

Python &735Set

Setup Progress

irstaitg
Pyateor 3.72 Tel% Saprt (32-tit}

python
windows
Finally you will get successful installation message.

TECHNICAL PUBLICATIONS An up thrustfor knowledge


JENIL THAKKAR
Python Programming 1-5 Introduction, Data Types and Operators

Setup was successful


Sgecil thanks to Mar* Harond, without whose years
reely shared Windows expertise Python for Wisdows would

Disele sath lerngts sirait

python
windows
Congratulations!. The Python is installed on your PC. Now you can write and
execute the programs in Python using Python Shell.
Go to the List of Applications in your PC, Locate Python, either click on Python o
IDLE to get the shell prompt. I use Python IDLE. The shell prompt appears as follows

Fe kdit he
ww.verewawww.e
egptionsii He
vowww.wv

sor*oe*enonnene*enneowewioonwwwwww.svw*www.wwwwww. **wwww****ww**www.w.

Python 3.7.3 (v3.7.3:ef4ec:6edi2, Mar 25 2019, 21:26


5 3 MSC V.1916 32 bit (Intel} win32
Type " ILelp",copyxight", r e d Í t a * or *iicense {}*
for nore infoInatio.

********************** ************************
*****************i*vr ******

**..."

TECHNICAL PUBLICATIONS®- An up thrustfor knowledge


JENIL THAKKAR
Python Programming
1 -6
Introduction, Data pes
The Python shell will be displayed and >>> prompt will be displayed.
and Operato
One can type
different programming constructs and get the instant result of the commanaan
Pyt
entere Por
example
Pythen 73 Shel
e
wwww.w*w
dt vw
She eag tions ndes
mv wwooevoeveovi o**wwww*v***** w*w*v*v***************** *************tstrnesesviarpre

,
6:53 MSC v. 1916 32 bit {Intel. On win32
TYpe "help", "copyright", "credits" or "license ()

Meii, XCited to earn Python

00oooo00o00o0oeooooooooeoooooocoocooooooocooooooooooodocoocosoocoo

In above command have used


we print command to display the desired message at
the prompt.
The last line is a prompt that indicates that the interpreter is ready for you to enter
code. If you type a line of code and hit Enter, the interpreter displays the result. For
example

s e
wwww.
vwwwwww*wwwwwvvw*ww.***************w***********************************v**w**w**ov*v*i vAvev wv ww.w**********
*w.www. wwAww*

2+3

v******************************
********************* ************v **w.v* v ** w *******

ooscoooddoeocoodocoooooooocccoo

1.2.1 Modes of Working in Python


Python has two basic modes : normal and interactive.
1) Interactive mode
f e e d b a c

Interactive mode is a command line shell which


45

each statement, while gives imme memory.

running previously fed statements ln auated bothin a c t i v e


p a t

new lines are fed into the both


and in whole.
interpreter, the fed program 1s
eva

TECHNICAL PUBLICATIONS
JENIL THAKKAR
-
An up thrust for knowledge
Python Programming 1-7 Introduction, Data Types and Operators
The > is Python's way of telling you that you are in interactive mode. In
interactive mode what you type is immediately run. For example - If we type 1+1

on the interpreter the immediate result i.e. 2 will be displayed by interpreter.

e Sot She ebag ptons incdow ielp

>>> i+
2
ww.wwvwatsoyotn

Lns15 Cok 4
2) Script mode

This is also called as normal mode. This is a mode in which the python commands
are stored ina file and the file is saved using the extension py
For example: We can write a simple python program in script mode using
following steps
Step 1: Open python Shell by clicking the Python IDE.

Step 2: On File Menu Click on New File option.

Python 373Shel
File Edit Sheli Debug Gptions Winsiow Help
veceicwwwecoverwwercicrww vvicwwwww.

3:ef4ec6ed12, Mar 25 2019, 2


Open Ctrl+O 6 32 bit (Intel)1 on win32
Open Module. At+M ight", "Cedits" or "iicenSe
Recent Files
Module Browser AtC ation.
Path Browser
wwwwar

Save
Save As Ct+ Shift+
Save Copy As.Ait-Shifts
r2221019wMnwwwssss ss*wmwwwwwmmmnwmmw
Prit Wirrdn
varnnnin

w.v wvww
Close At F4 Ln:3ol:4

Step 3: Give some suitable file name with extension.py (I have created
test.py).
Step 4: A file will get opened and the tyr some programming code. Sample file is as
follows-

JENIL THAKKAR
TECHNIrAI PUBLICATIONS "hrije "ar unnilnrtra
Python Programming 1-8 Introduction, ata ypes
and
Operaton
*****
ww.w.

********************************** **v*****ivi********
*******************°***********i eva4 ci
Pythor
.

1.3
i n t {2+3}

ww.wwwwwwwmw wwww wwwww.. ww ewwww.vaww*avwamw M


wewww.coeeo wwww.wwww**********************************sv*swesnvosoossooroeesrs ....

Step 5: Now run your code by clicking on Run ->Run Module on


Following screenshot illustrates it Menu bar.
bar

w w.*

wwww.
**** ww ravwnnwwwwwwvwwo ew.wwwwwwvww*w**e*v****** *v0**wv*w*wwwww.eresevesee*wwwweeovoee

print *Now
xint 2+3

882888888808E388888888888S6S68855085 33888888888888888886688 588885808000


For running the script we can also use F5
key.
Step 6 The output will be displayed on the
python shell. It is as followss
hon
el
www.rveneerw.vevweovw*********************************"***********""********"**
1:26:53) MSC v.916 32***ewrbit evwwwwiww wvtIntei
veveeawvweiv*t*AY***w********
*******vw.
Onvw Wii3
wwww.wwvwww****
TYpe help", "copyright",
* for more "credits" or "licen
information.
RESTART: C:/Users/Puntambe kar/AppData/Loca
L/PI
ograms/Python/Python37-32/test..py
Hello
Now
friends,
adding first Python Prog wo
this is my : am
nmibers and i
5 spiayång t.ie **

TECHNICAL PUBLICATIONS
An up thrust for
JENIL THAKKAR knowledge
and Operators
Python Programming
7-9
Introductlon, Data Types and Operators
-

* * * ** * * *
13 Variables
****

.
Definition:A variable is nothing but a reserved memory location to store values.
Variable is an entity to which the programmer can assign some values.
Programmer choose the variable name which is meaningful. For example :

. In the following example we have declared the variable count to which value 10 is
assigned with. This value is displayed by passing the variable name to print
statement.

***

enu bar.
The variable count is assigned with
9>Cou1t=10
print icount} value 10 and then using print
statement it is displayed
************************.************************.*********.

iCa

We can re-declare the variables for assigning different values. For example
>count =10
>»> print(oount)
10
The variable count is initially assigned with
>cout = 1000 10 and then re-assigned with the value 1000
print(count)
1000

Rules for variable names


Variable names must be meaningful. The variable name normally should dernote
its purpose. For example - if the variable name is even_count, then clearly total
number of even elements is stored in this variable.
The variable names can be arbitrarily long. They contain both letters and digits
but
they cannot start with a number.
Normally variable name should start with lower case letter.
ne
The underscore character is allowed in the variable name. For example - int

total_elements
4 Data Types in
Python
Data types are used to define type of variable.
********

JENIL THAKKAR
TECHNICAL PUBLICATIONS- An up thrust for knowledge
Python Programming 1 10 Introduction, Data Types and Operators
ln Python there are five types of data type that are used commonly and those are
Data types

Numeric String List Tuple Dictionary


Fig. 1.4.1 Data types in Python

Numeric: Python numericdata type is used to hold numeric values like;


nt- holds signed integers of non-limited length.
long- holds long integers
float holds
floating precision nunmbers and it's accurate upto 15 decimal places.
-

complex - holds complex numbers.

in Python we need not to declare datatype while declaring a variable like C or C+. We
can simply just assign values in a variable. But if we want to see what type of numerical
value is it holding right now, we can use type0. For example -

******************w**w*wwwww.iovonovwww.vwwawnwwww.wwww.wwwrovemerowwww.www.roesroowesow
ww.wwww.*wwwwwwwwwww***rw*****v**********w*****************************************
rete3 2 Vriaie i h integer välu :

print ("Type of variable a is: ", type (a))


las *int *»
D> ËIEate v a r a b i e wi.th £3oat value
=15.1234

SS 'float'>

print("Y E Vari.abie s : " , V e {e

wrasodeegitidti
sesestve+0023*1tttta***1**00************************************0******************A***********A* w***vii** ****ii***** *************S*************

*www ..*

(2) String8:
String is a collection of characters.
In Python, we can use single quote, quote or triple quote to define a string double
We can use two operators along with the string one is + and
another is*.

JENIL THAKKAR
TECHNICAL PUBLIOCATIONS- An up thrust for knowledge
Python Programming
1-11 Introduction, Data Types and Operators
The+Operator is used to concatenate the two strings. While *operator is used as a
repetition operation.Followingexecution illustrates it

wwwww ********
wwww..wwww
ww
* W *** ***"*************************************i** *a*e**etvve

stx2 yon*
> print (strI}
My
print {str2}}
Python
print (strl+str2)
MVPython
> print (str2*3
PythonPythonPython
www.****** * * * * * * * **
*********************

****************w*****w*wwww.**********n** m*eron*o***nesve*wwwsrs orerss

www

(3) List
I t is similar to array in C or C++ but it can simultaneously hold different types of
data in list.
tis basically an ordered sequence of some data written using square brackets(1)
and commas(,)
For example -

Bython 273
*********** *********************************************************************************************************

a[10, 20, 30,40,501


print {a)
110, 20, 30, 40, 501
i s t of oniy stIingS

SER, Mon*, Tue'


s t of both integers and string
C 1 1 , *Red,"reen", 2,3,
int {c}
L, Red, 'Green', 2 3
aeon eoanomoonoonwwnw.mw..smononmwmwr.msmnenonporoononronns*xeonw*w*tns* ************.*MAN
iiHN miH t
wwww wwww. wwwwwwwwwwwww.wwwwww
**www*** wwww.wwe

TECHNICAL PUBLICATIONS-An up thrust for knowledge

JENIL THAKKAR
Python Programming 1-12
Introduction, Data Types and
(4) Tuple
Operators
Tuple is a collection of elements and it is similar to the List. But the items of #
tuple are separated by comma and the elements are enclosed in ) parenthesis the
Tuples are immutable or read-only. That means we can not modify the size
of
tuple or we cannot change the value of items of the tuple.
Here are examples of tuples -

Pythen 3z3 Shell www

****************w*****************w**ww***Awwwwwwwwwwwwwww*wwwwwwwwwwwwwwwwww*wwwwww** **tr*****V**************0******9************************0w**** mnewww. ****

>>> a=(10, 20,30,40,50)

(10, 20, 30, 40, 50)


>>*Tupie f o t h integersand stringgs
>>> e * , I, , * xee *. 3
> p i n t {b}
("one", 1, 2, 'two', 'three', 3)
>>>print (b[3] )

*oowwwwwrooo

5) Dictionary
.Dictionary is a collection of elements in the form of key:value pair.
The elements of dictionary are present in the curly brackets.
For example -

www.w..rer
*******************************************w****err*i
niw*N*w**ieresn* to****m itm *mnmwnw*wm ww:*wNm wawwwwwwwwwwwwwwwww w wawwwwww.wwwwwwwww..www***********

2={î:*Red' ,2: 'Eiue,3:*Creen*}


> print {a
{1: 'Red', 2: 'Blue', 3:Green'}}
>>»print(a.keys ())
dict keys { [1, 2, 31I
****

>> print (a.vaiues (}}


dict values (i*Red, Bi ue', *
Green'}
www *w%

JENIL THAKKAR
TECHNICAL
PUBLICATIONSAn up thrust for knowledge
Python Programming 13 Introduction, Data Types and
Operators
1.5 Input Operationss
I n python it is possible to input the data using keyboard.
For that purpose, the function input) is used.

Syntax
input(Iprompt|)
where prompt is the string we wish to display on the screen. It is optional.

Example 1.5.1 Inthefollowing screenshot,theinputmethodisused togetthe data


Solution:

*********************

******** *************.....*******************************oss*************.osn .o**eanaanre..oene... ... .....

Example 1.5.2 Writea Python progranto perform additio oftwo numbers Accept the two
numbers using keyboard

Solution
addition.py

Eile
w Edit Format Run Qptions Window He
print ("Enter first number") ****

a=int(input {))
print ("Enter second number")
b=int(input ())
C +
print ("The addition of two numbers is: ")
print (c}

*NA**NN**A wawwwwww.ww

Sswww

JENIL THAKKAR
TECHNICAL PUBLICATIONS-An up thrust for knowledge
Python Programming 1-14
Introduction, Data Types and
Output Operators
For getting the output click on Run-> Run Module or press F5 key, follos
window will appear - llowing shel
ww
**************************v *w*******i**wwww.***w*******ww***************************************************************************tdidror trorert vos

3
*********************************** io***. ******** ** .** ** **** *********************************************"***************** ********** ************ .

wwww.w.

Program Explanation
In above program, we have used
input) function to get the input through
keyboard. But this input will be accepted in the form of string
For performing addition of two numbers we need
numerical values and not the
strings. Hence we use int() function to which the input() function is passed as
parameter. Due to which whatever we accept through keyboard will be converted
to integer.

Finally the addition of two numbers as a result will be displayed.


The above program is F5 and
run
using on the shell window the
messages for
entering first and second numbers will be displayed so that user can enter the
numbers.

Example 1.5.3Write a Python program to find the square root ofa given number
Solution:
SqrtDemo.py
print('Enter the number:")
num=float(input()
result=num* *0.5
print("The sqaure root of "num," is "result)
Output
Enter the number:
25
The sqaure root of 25.0is 5.0

Example 1.5.4 Write a program in Python to obtain principle amount, rate of interestand tie
from user and compute simple interest.

TECHNICAL PUBLICATIONS -An up thrust for knowledge

JENIL THAKKAR
Python Programming 1- 15 Introduction, Data Types and Operators
Solution
Interest.py
print("Enter principal amount:")
p=loat(input()) Here we are reading the values through
print("Enter rate of interest: ") keyboard. Note we are reading the
r=float(input()) values as float
print("'Enter number of years: ")
n=float(input())
I=(p°n*r)/100
print('Simple Interest is: "I) # Output will be displayed on console

Output

gedit
wwwww.wwww.ww.wwww.
ekbsaggtions d o e e s
** ****wwwww wsw*wwwwwww.w.wwwwwnvwwoww.wwww.wooww.wwwowoww.oworoenoowww.
Enter principai anount:
1000
Enter rate o interest:
6.5
nter KAEX years

Sinpie InteIeSt i3: 325.


*************************************www..*www..omm www.ww.www.ww.
****w**w**w.*************** ******************************************w*

1.6 Comments
Comments are the kind of statements that are written in the
program for program
understanding purpose.
By the comment statements it is possible to understand what exactly the
program
is doing.
In Python, the hash (#)
we use
symbol to start writing a comment.
It extends up to the newline character.
Python Interpreter ignores comment.
ForFor example
# This is comment line
print("I love my country")
If we have comments that extend
multiple lines, one way of doing it is to use hash
(F) the beginning of each line. For example
in
#This is
#another example
#of comment statement

TECHNICAL PUBLICATIONS- An up thrust for knowledge


JENIL THAKKAR
Python Programming 1- 16 Introduction, Data Types and Operator
1.7 Reserved Words ators
The keywords words reserved for
are special some purpose. The pythona
following list of keywords has
False class fually
continue lambda
def nonlocal while
del not

Or
else pass
exceptt
alse
The names of keywords be not be used
can as variable nanme. For instance a variable
name can not be from because it is a
keyword.
1.8 Indentation
Leading white space at the beginning of the logical line is called indentation.
Python programs get structured through indentation, i.e. code blocks are defined
by their indentation.
All statements with the same distance to
the right belong to the same block of
code, i.e. the statements within a block line up
vertically.
If a block has to be more
deeply nested, it is simply indented further to the right.
For example -
age = int(input(How old are you? ))
if ag e <= 2:

print Infant) Here the line is indented that means


this statement
will execute only if the if
statement is true

1.9 Perform Computations and Create Logical Statements using Python's


Operators
Operands special symbols that are used in computations. For
are

and/ are used for performing arithmetic operations.


example t
The values that operator uses for performing computation are called
Various operators used in Python are described as follows
operands.

1.9.1 Arithmetic Operators


These operators are used for performing arithmetic operations.

TECHNICAL PUBLICATIONS An up thrust


JENIL THAKKAR for knowledge
Python Programming 1-17 Introduction, Data Types and Operators
Operator Meaning Example
Addition operatoris used for performing addition oftwo 10+20-30D
mumberS.

Subtracton operatoris used for performing subtraction 20-10-10


Multiplicationoperatorisusedfor performing 1010-100
multiplication
Division operator is used for performing divisionoftwo 10/2
umbers
Modoperator returmstheremainder value 0%20

This isanexponentiationoperator(power) 2
Thisisfloor divisionoperator.In thisoperation the result
is the quotient in whichthe digits after the decimal point
are removed

For example
>>> 10+20
30
>>> 20-10
10
>>> 10/2
5.0
>>>5*10
50
>>>2**3
8
>>> 9//2

>>>

1.9.2 Comparison Operators


The operators compare the values and establish the relationship among them.

er Meaning
If two vaues are egualthen conditionbecomes true

If two operands arenotequal thentheconditionbecomestrue


Thisissimilarto Thatmeansiftwovaluesare notequalthenitreturnstrue
This is lessthan operator.f left operand is lessthan the right operatorthen the
return value is true

JENIL THAKKAR
TECHNICAL PUBLICATIONS-An
thrust for knowledge
up
Python Programming 1 - 18 Introduction, Data Types and Operators
tors
This is greater than operator. If left operand is greater than the right operator then

the return value is true


than the right operatora
This is less than equal to operator. If left operand is less
equal to the right operator then the return value true
is

right operator
This is greater tharn equal to operator. Ifleft operand is less than the
return value is true
or equal tothe right operator then the
For example -

>>> 10<20

True
>>> 10<=10
True
> > > 20>10

True
> > > 20>=10

True
>>>

1.9.3 Logical Operators


or, not
There are three types of logical operators and,
Example
Meaning
Operator is true
a and b
the entire expression
If both the operandsare true then
operand is true
Ifeitherfirst orsecond
entireexpressionis true
Ifthe operand is false then the

For example
>>>a=True

> > > b = F a l s e

>>>a and b
False
>>>a or b
True
> > > not a

False

ers
1 . 9 . 4 Bitwise O p e r a t o r s
binary numoe
value. These bits
are
w o r k o n the
bits of the given
Bitwise operators
1.
i.e. 0
or

An up thrust for knowledge

JENIL THAKKAR
PUBLICATIONS-
TECHNICAL
Python Programming 1-19 Introduction,Data Types and Operators
For example: The number 2 is 010, 3 is 011.

Operator Meaning Example If a 010,b 011

This is bitwise and operator a&b 010

This is bitwise or operator alb 011

This is bitwise not operator a=101


This is bitwise XOR operator The a xorb 001
binary XOR operation will always
produce a1 output if either of its inputs
is 1 and will produce a 0 output if both
ofitsinputs are 0 or 1

The left shift operator 1-010k<l means make lett shift by


one positons
and adda tatingzero
010
100
decimal 4

Theright shift operator as1010>1meansmake right shift by


oneposition and add leadingzero.

decimal

1.9.5 Assignment Operators


The assignment operator is used to assign the values to variables. Following is a ist of
assignment operators.
Operator Example and Meaning

Thisis an operator using which values is assigned toa variable


a5

a+5means a= a+5

a-5means a =a 5

JENIL THAKKAR
TECHNICAL PUBLICATIONS- An up thrust for knowledge
Python Programming 1-20 Introduction, Data Types and Operators

Similarly *=, = operators are used for performing arithmetic multiplication and

division operation.
Example 1.9.1 Write a program in Python to print aren and perimeter of acircle
Solution:
areaDemo.py
print("Enter radius os a circle: ")
r=float(input())
PI = 3.14

area= PI'r*r

perimeter= 2.0*PI*
print("Area of Circle = ",area);

print("Perimeter of Circle = ".perimeter)

Output

ww%
wwwwwvwwvwwwwwww.wwwwwrvvaV***Y**vw***********************

***www.************
wwww.********************** **************"

RESTART: C:/Users/Puntanbekar/Appat.a/LCaL/PIograRS/PY

thon/Python3732/arealeno.PY

Area of Circie= 314.


Circle = 62.800000000000004

wwww*NvY**w*w**eO*V************w*********************************************************************** **wwwwwwwwwwww*wwww*w***A*A*******************

parallelogram
Example 1.9.2 Write a programto find area and perimeter of
Solution: Formula for finding area arnd perimeter of
parallelogram is
Area= b'h
Perimeter = 2*b+2*w N

We can write the python program using above


formula

areaDemo.py b
print("Enter height(h):")
h=float(input())
print ("Enter base(b): ")
b=loat(input(0)
print("Enter width(w): ")
w-float(input()
area= b'h
perimeter= (2.0"b)+(2.0 w)

TECHNICAL PUBLICATIONS An up thrust


JENIL THAKKAR for knowledge
Python Programming 1-21 Introduction, Data Types and Operators
print('Area of Paralelogram = ",area);
print("Perimeter Parallelogram = "perimeter)

Output
Enter height(h):

10

Enter base(b):
20
Enter width(w):
15
Area of Parallelogram = 200.00

Perimeter Parallelogram = 70.0

Example 1.9.3 Writea program to convert Fahrenheit to Celsius


Solution We will use the following formula for conversion
Celsius (Fahrenheit 32)/1.8
Temp.py
print("Enter Fahrenheit ")
f=loat(input())
c= (1-32)/1.8
print("Celsius = ",c)

Output
Enter Fahrenheit
95.5
Celsius = 35.2777

1.9.6 Membership Operators


in and not in
types of membership operators
-

There are two


These operators are used to find out whether a value is a member of a sequence such

as string or list.

Operator Description
in It returns True if a sequence with speified value is present in the object

not in t returns true if a sequence with specified value is not presentin the object.

TECHNICAL PUBLICATIONS - An up thrust for knowledge

JENIL THAKKAR
Python Programming 1-22 Introduction, Data Types and
Following screenshot of Python
shell shows the use of in and non in o Operators
erator.

dit She esg i n s ndew teip


e

>> Color = ["red", "blue", "green"]


>>> pr int "bine" in Coior}

>print ("yeiiow" àn Coior)


aise
>> print ("yeiiow* o t in Coior
True
wwwwwwwwwec vseswosveoowwwww..esoessittwwwee eovovwwrr wwwww.ww.ww** ****************************************** *****iiiiie*dtiiédcosezorvddiier

Explanation
1) In example, we have created a list of colors.
2) The members of color list are "red","blue" and
"green"
3) As "blue" is member of color
list, it returns True for while testing with
membership operator in operator.
4) As "yellow" is not a member of color
list, it return False for in operator and ine
for not in
operator.
1.9.7 Identity Operators
The is
operator returns true if both the
Similarly 'is noe' operator operand point to same memory a cation.
returns true if both the operand
location. point to difterent

*>>
*w*w* * vw* * * * * * * * *w* *ew* * r*wwnetv ene ae enwwmrwwwweewwwwwwwwwwwwwwwwww*w*ww..* * wwwwwww%
www

COlori
Color2 Ei", "si3, "XEeN"
{"red","
=

>>> color3=colorî
,areeni
print (colori s
False color2)
T
print
e (colorl is
color3)
w.ww.*

JENIL THAKKAR
TECHNICAL
PUBLICATIONS An up thrust for knoweog
Python Programming 1-23 Introductlon, Data Types and Operators
Similarly,
>>> print(color1 is not color2)
True

Explanation: In above demonstration,


1) We have created two lists color1 and color2.
2) Although the contents of the lists are exactly the same, their memory locations are
different. Hence colorl is color2 becomes False.
3) As color3 is a new variable to which we assign color1, then they point to same
memory location. Hence color1 is color3 returns True.

1.9.8 Modulus Operator


The % operator is a modulo operator that gives the remainder from the division of first
argument by second.
For example
>>> 10%3
1
>>> 10.10%3.3
0.20000000000000018
>

The operator // is used for floor division. This division returns the integral part of the
quotient.
For example-
>>>10//3.5
2.0

Example 1,94 Writeaprogramin Python toconoert


ww giventimeintominutes andsecornds.For
example userinputs260secondsthentheoutpiutshouldbe 4minute and20seconds
TUse //and % operators

Solution:
timeDemo.py
print("Bnter time: ")
time=loat(input())
minutes= time//60
seconds= time %60
print 'Minutes are: "minutes)
print('Seconds are: ",seconds)

JENIL THAKKAR
TECHNICAL PUBLICATIONS An un thrustfor knowledge
Python Programming 1-24 Introduction, Data Types and Operatos
arators
Output

d t She ebag stiens ckow ep


* w w***** vww*vw*ww.wwww**V****Www*w*w********* ***********************************************2m**rsssanvarss
w..w...

RESTART: C:/Users/Puntanbekar/AypData/IOcal/Programs/Py
thon/Python37-32/timeDenO.pY
Enter tine:
260
MinteS are: 4.0
SecondS are: 20.0
********wwww.w*vww.www.wwwvewww.wvww...
************************* wwwwwwwwwwww*************w*******tv******SOOe***sO****Y*****w*tiSR**evi*****i*O**vtv**teticotateivts oswwwrveo.

1.9.9 List, Tuple and String Operators


The List, Tuple and
string makes use of the operators such as+and*.
I n python it is possible to
perform the concatenation and repetition operations on
strings using the operators like + and*.
For example
>>>str1="Hello"
>>> str2="friend"
>>> str1+str2

Hellofriend'
>>>"welcome*2
welcomewelcome'

TECHNICAL PUBLICATIONS- An up thrust


for knowledge
JENIL THAKKAR

You might also like