Chapter - 1 Introduction, Data Types and Operators
Chapter - 1 Introduction, Data Types and Operators
... 1 - 15
1.6 Comments....
...1-22
1.9.7 Identity Operators.. °°°**°°*.
..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-1)
JENIL THAKKAR
Python Programming 1-2 Introduction, Data Types and Operators
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
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
staNW
sesttardekariApARaidcaiPrgPYPAaPAan372
**
mize iristaaatiorn Step 2: (Kk t»
wwwwwawewwem
Ste Ceckths
python
windows ****************
Python &735Set
Setup Progress
irstaitg
Pyateor 3.72 Tel% Saprt (32-tit}
python
windows
Finally you will get successful installation message.
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.
********************** ************************
*****************i*vr ******
**..."
,
6:53 MSC v. 1916 32 bit {Intel. On win32
TYpe "help", "copyright", "credits" or "license ()
00oooo00o00o0oeooooooooeoooooocoocooooooocooooooooooodocoocosoocoo
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
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
>>> 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.
Python 373Shel
File Edit Sheli Debug Gptions Winsiow Help
veceicwwwecoverwwercicrww vvicwwwww.
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}
w w.*
wwww.
**** ww ravwnnwwwwwwvwwo ew.wwwwwwvww*w**e*v****** *v0**wv*w*wwwww.eresevesee*wwwweeovoee
print *Now
xint 2+3
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
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
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 :
SS 'float'>
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.****** * * * * * * * **
*********************
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
*********** *********************************************************************************************************
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 -
*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***********
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.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.
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.
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
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
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:
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
>>>
er Meaning
If two vaues are egualthen conditionbecomes 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
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
>>>
For example
>>>a=True
>>>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
JENIL THAKKAR
PUBLICATIONS-
TECHNICAL
Python Programming 1-19 Introduction,Data Types and Operators
For example: The number 2 is 010, 3 is 011.
decimal
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);
Output
ww%
wwwwwvwwvwwwwwww.wwwwwrvvaV***Y**vw***********************
***www.************
wwww.********************** **************"
RESTART: C:/Users/Puntanbekar/Appat.a/LCaL/PIograRS/PY
thon/Python3732/arealeno.PY
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
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)
Output
Enter height(h):
10
Enter base(b):
20
Enter width(w):
15
Area of Parallelogram = 200.00
Output
Enter Fahrenheit
95.5
Celsius = 35.2777
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.
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.
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
The operator // is used for floor division. This division returns the integral part of the
quotient.
For example-
>>>10//3.5
2.0
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
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.
Hellofriend'
>>>"welcome*2
welcomewelcome'