Module 1 Python
Module 1 Python
MODULE - I
Agenda:
Python Basics,
Getting started,
Python Objects,
Numbers,
Sequences:
Strings,
Lists,
Tuples,
Set and Dictionary.
Conditionals and Loop Structures
Python is a simple programming language. When we read Python program, we can feel like
Reading English statements. The syntaxes are very simple and only 30+ keywords are
available. When compared with other languages, we can write programs with very less
number of lines. Hence more readability and simplicity.
We can use Python software without any licence and it is [Link] source code is
open,so that we can we can customize based on our requirement.
Eg: Jython is customized version of Python to work with Java Applications.
Platform Independent:
Once we write a Python program, it can run on any platform without rewriting once again.
Internally PVM is responsible to convert into machine understandable form.
Portability:
Python programs are portable. ie we can migrate from one platform to another platform
very easily. Python programs will provide same results on any paltform.
Dynamically Typed:
In Python we are not required to declare type for variables. Whenever we are assigning the
value, based on value, type will be allocated [Link] Python is considered as
dynamically typed [Link] Java, C etc are Statically Typed Languages because we
have to provide type at the beginning only.
Extensible:
We can use other language programs in Python,The main advantages of this approach are:
1. We can use already existing legacy non-Python code
2. We can improve performance of the application
Embedded:
We can use Python programs in any other language programs. i.e we can embedd Python
programs anywhere.
Extensive Library:
Python has a rich inbuilt [Link] a programmer we can use this library directly and we
are not responsible to implement the functionality.
Versions of Python:
Python Applications:
The following are different area we can use python programming language
In Python 2 the following 2 functions are available to read dynamic input from the
keyboard.
1. raw_input()
2. input()
1. raw_input():
This function always reads the data from the keyboard in the form of String Format. We
have to convert that string type to our required type by using the corresponding type casting
methods.
Eg:
2. input():
input() function can be used to read data directly in our required [Link] are not required
to perform type casting.
Eg:
x=input("Enter a Value)
type(x)
20 ===> int
"DS"===>str
125.5===>float
True==>bool
In Python 3 we have only input() method and raw_input() method is not available.
Python3 input() function behaviour exactly same as raw_input() method of Python2.
i.e every input value is treated as str type only.
Example:
x=input("Enter First Number:")
y=input("Enter Second Number:")
a = int(x)
b = int(y)
print("Sum=",a+b)
output:
Enter First Number:10
Enter Second Number:20
Sum=30
OutPut Function:
We use the print() function or print keyword to output data to the standard output device
(screen). This function prints the object/string written in function
Examples:
print("Hello World")
We can use escape characters also
print("Hello \n World")
print("Hello\tWorld")
We can use repetetion operator (*) in the string
print(10*"Hello")
Reserved Words
In Python some words are reserved to represent some meaning or functionality. Such
type of words are called Reserved words.
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.
In Python, keywords are case sensitive.
There are 33 keywords in Python 3.7. This number can vary slightly over the course
of time.
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.
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
1. Decimal form(base-10):
It is the default number system in Python
The allowed digits are: 0 to 9
Eg: a =10
2. Binary form(Base-2):
The allowed digits are : 0 & 1
Literal value should be prefixed with 0b or 0B
Eg: a = 0B1111
a =0B123
a=b111
3. Octal Form(Base-8):
The allowed digits are : 0 to 7
Literal value should be prefixed with 0o or 0O
Eg: a=0o123
a=0o786
Example:
>>> a=10
>>> b=0B0101
>>> c=0o121
>>> d=0xabc
>>> print(a)
10
>>> print(b)
5
>>> print(c)
81
>>> print(d)
2748
Base Conversions
Python provide the following in-built functions for base conversions
[Link]():
We can use bin() to convert from any base to binary
Eg:
>>> bin(5)
'0b101'
>>> bin(0o11)
'0b1001'
>>> bin(0X10)
'0b10000'
2. oct():
We can use oct() to convert from any base to octal
Eg:
>>> oct(10)
'0o12'
>>> oct(0B1111)
'0o17'
>>> f=0o123.456
SyntaxError: invalid syntax
>>> f=0X123.456
SyntaxError: invalid syntax
5. str type:
str represents String data type.
A String is a sequence of characters enclosed within single quotes or double quotes.
s1='MREC'
s1="MREC"
By using single quotes or double quotes we cannot represent multi line string literals.
s1="MREC DS"
For this requirement we should go for triple single quotes(''') or triple double
quotes(""")
s1='''MREC
DS'''
s1="""MREC
DS"""
We can also use triple quotes to use single quote or double quote in our String.
>>> s1='''"This is mrec"'''
>>> s1
'"This is mrec"'
We can embed one string in another string
>>> s1='''This "Python Programming Session" for DS Students'''
>>> s1
'This "Python Programming Session" for DS Students'
Slicing of Strings:
slice means a piece
[ ] operator is called slice operator,which can be used to retrieve parts of String.
In Python Strings follows zero based index.
The index can be either +ve or -ve.
+ve index means forward direction from Left to Right
-ve index means backward direction from Right to Left
Eg:
-7 -6 -5 -4 -3 -2 -1
>>> s[1:4]
'REC'
>>> s[0:4]
'MREC'
>>> s[0:]
'MREC DS'
>>> s[:4]
'MREC'
>>> s[:]
'MREC DS'
>>> len(s)
7
Type Casting in Python
We can convert one type value to another type. This conversion is called Typecasting or
Type conversion.
The following are various inbuilt functions for type casting.
1. int()
2. float()
2. float():
We can use float() function to convert other type values to float type.
We can convert any type value to float type except complex type.
Whenever we are trying to convert str type to float type compulsary str should be
either integral or floating point literal and should be specified only in base-10.
Eg:
1) >>> float(26)
2) 26.0
3) >>> float(True)
4) 1.0
5) >>> float(False)
6) 0.0
7) >>> float("26")
8) 26.0
[Link]():
We can use complex() function to convert other types to complex type.
We can use this function to convert x into complex number with real part x and
imaginary
We can use this method to convert x and y into complex number such that x will be
real part and y will be imaginary part.
Eg:
1) complex(26)
26+0j
2) complex(26.26)
26.26+0j
3) complex(True)
1+0j
4) complex(False)
0j
5) complex("26")
26+0j
6) complex("26.26")
26.26+0j
7) complex("MREC")
ValueError: complex() arg is a malformed string
8)complex(26,26)
26+26j
9)complex(True,False)
1+0j
4. bool():
We can use this function to convert other type values to bool type.
Eg:
1) bool(0)
An operator is a symbol that tells the compiler to perform certain mathematical or logical
Manipulations. Operators are used in program to manipulate data and variables.
Python language supports the following types of operators.
1. Arithmetic Operators
2. Relational Operators or Comparison Operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Special operators
1. Arithmetic Operators:
Arithmetic operators are used with numeric values to perform common mathematical
operations:
/ operator always performs floating point arithmetic. Hence it will always
returns float value.
Floor division (//) can perform both floating point and integral arithmetic. If
arguments are int type then result is int type. If at least one argument is float
type then result is float type.
Assume variable „x‟ holds 5 and variable „y‟ holds 2, then:
Operator Name Example
+ Addition - Adds values on either side of the operator x + y=7
Subtraction - Subtracts right hand operand from left hand
- x – y=3
operand
Multiplication - Multiplies values on either side of the
* x * y=10
operator
Division - Divides left hand operand by right hand
/ x / y=2.5
operand
Modulus - Divides left hand operand by right hand
% x % y=1
operand and returns remainder
Exponent - Performs exponential (power) calculation on
** x ** y=25
operators
Floor Division - The division of operands where the result
// is the quotient in which the digits after the decimal point x // y=2
are removed.
Eg:
>>> x=5
>>> y=2
>>> print('x+y=',x+y)
x+y= 7
3. Logical operators:
Logical operators are used to combine conditional statements:
X Y X AND Y X OR Y NOT X
False False False False True
False True False True True
Ture False False True False
True True True True False
Eg:
>>> x=5
>>> y=2
>>> x and y
2
>>> print(x>=5 and y<=5)
True
>>> print(x>=5 or y<=5)
True
>>> print(not x>=5)
False
4. Bitwise operators:
Bitwise operator works on bits and performs bit by bit operation.
We can apply these operators bitwise on int and boolean types.
By mistake if we are trying to apply for any other type then we will get Error.
Eg:
>>> x=5
>>> y=2
>>> print('x & y=',x&y)
x & y= 0
>>> print('x | y=',x|y)
x | y= 7
>>> print('X ^ y=',x^y)
X ^ y= 7
>>> print('~x=',~x)
~x= -6
>>> print('x>>1=',x>>1)
x>>1= 2
>>> print('y<<1=',y<<1)
y<<1= 4
[Link] operators:
Assignment operators are used to assign values to variables:
5. Special operators:
Python defines the following 2 special operators
1. Identity Operators
2. Membership operators
Operator is: It returns true if two variables point the same object and false
otherwise
Operator is not: It returns false if two variables point the same object and true
otherwise2 identity operators are available.
Operator Description Example
is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y
Eg:
>>> x=5
>>> y=5
>>> print(x is y)
True
>>> print(id(x))
2265011481008
>>> print(id(y))
2265011481008
>>> print(x is not y)
False
2. Membership Operators
These operators test for membership in a sequence such as lists, strings or
tuples. There are two membership operators that are used in Python. (in, not
in). It gives the result based on the variable present in specified sequence or
string
For example here we check whether the value of x=4 and value of y=8 is
available in list or not, by using in and not in operators.
Operator Description Example
in Returns True if a sequence with the specified value is x in y
present in the object
not in Returns True if a sequence with the specified value is not x not in y
present in the object
Example:
>>> exp=10+20*30
>>> print(exp)
610
Example:
>>> exp=100/10*10
>>> print(exp)
100.0
Please see the following precedence and associativity table for reference. This table
lists all operators from the highest precedence to the lowest precedence.
Operator Description Associativity
() Parentheses left-to-right
** Exponent right-to-left
* / % Multiplication/division/modulus left-to-right
+ – Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
is, is not Identity left-to-right
in, not in Membership operators
Conditional statement
Conditional statements will decide the execution of a block of code based on the
expression.
The conditional statements return either True or False.
A Program is just a series of instructions to the computer, But the real strength of
Programming isn‟t just executing one instruction after another. Based on how the
expressions evaluate, the program can decide to skip instructions, repeat them, or
choose one of several instructions to run. In fact, you almost never want your
programs to start from the first line of code and simply execute every line, straight to
the end. Flow control statements can decide which Python instructions to execute
under which conditions.
Python supports four types of conditional statements,
1) Simple if or if statement
if condition : statement
or
if condition :
statement-1
statement-2
statement-3
If condition is true then statements will be executed
Example:
>>> a=10
>>> b=5
>>> if(a>b):
print("a is big")
a is big
>>> if a>b:
print("a is big")
a is big
2) if else:
if condition :
Statements-1
else :
Statements-2
if condition is true then Statements-1 will be executed otherwise Statements-2 will be
executed.
Example:
>>> a=10
>>> b=25
>>> if(a>b):
print("a is big")
else:
print("b is big")
Syntax:
if condition1:
Statements-1
elif condition2:
Statements -2
elif condition3:
Statements -3
elif condition4:
Statements -4
...
else:
Default Action
Based condition the corresponding action will be executed.
Example:
>>> Option=int(input("Enter a value b/w(1-5)"))
Enter a value b/w(1-5)2
>>> if(Option==1):
print("you entered one")
elif(Option==2):
print("You entered Two")
elif(Option==3):
print("You entered Three")
elif(Option==4):
print("You entered Four")
elif(Option==5):
print("You entered Five")
else:
print("Enter Value b/w (1-5) only")
4. nested if statement
We can use if statements inside if statements, this is called nested if statements.
Synatx:
Login successful:
Iterative Statements
If we want to execute a group of statements multiple times then we should go for Iterative
statements.
Python supports 2 types of iterative statements.
1. for loop
2. while loop
1) for loop:
If we want to execute some action for every element present in some sequence(it may be
string or collection)then we should go for for loop.
Syntax:
for x in sequence :
body
Where sequence can be string or any collection.
Body will be executed for every element present in the sequence.
Eg 1: To print characters present in the given string
>>> s="MREC"
>>> for r in s:
print(r)
M
1
2
3
4
5
2) while loop:
If we want to execute a group of statements iteratively until some condition false,then we
should go for while loop.
Syntax:
while condition :
body
1) break:
We can use break statement inside loops to break loop execution based on some
condition.
Eg:
for r in (1,2,3,4,5):
if(r==3):
print("Break the loop")
break
print(r)
OutPut:
1
2
Break the loop
2) continue:
We can use continue statement to skip current iteration and continue next iteration.
Eg 1: To print even numbers in the range 1 to 10
for r in (1,2,3,4,5,6,7,8,9,10):
if(r%2!=0):
continue
print(r)
OutPut:
2
4
6
8
10
4. r=range(0,5)
r[0]==>0
r[15]==>IndexError: range object index out of range
We cannot modify the values of range data type
[Link] data type:
If we want to represent a group of values as a single entity where insertion order
required to preserve and duplicates are allowed then we should go for list data type.
An ordered, mutable, heterogeneous collection of elements is nothing but list, where
Duplicates also allowed.
insertion order is preserved
heterogeneous objects are allowed
duplicates are allowed
Growable in nature
values should be enclosed within square brackets.
1. Eg:
Eg:
>>> d={1:"one",2:"Two",3:"Three"}
>>> d[1]
'one'
>>> d
{1: 'one', 2: 'Two', 3: 'Three'}
>>> d[4]="Four"
>>> d
{1: 'one', 2: 'Two', 3: 'Three', 4: 'Four'}
>>> d[5]="error"
>>> d
{1: 'one', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'error'}
>>> d[5]="Five"
>>> d
{1: 'one', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five'}
11. None Datatype:
The None Datatype is used to define the null value or no value, the none value
means not 0, or False value, and it is a data it's own
None keyword is an object and is a data type of nonetype class
None datatype doesn‟t contain any value.
None keyword is used to define a null variable or object.
None keyword is immutable.
Eg:
Assume a=10, that means a is the reference variable pointing to 10 and if I take a=none
then a is not looking to the object 10
>>> a=10
>>> type(a)
<class 'int'>
>>> a=None
>>> type(a)
<class 'NoneType'>