Basics of Python Programming
Literal Constants
The word literal has been derived from literally.
The value of a literal constant can be used directly in programs.
Numbers1
Number as the name suggests, refers to a numeric value.
i) Integer
Example:
10
>>> type(10)
<class 'int'>
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 1
Techno Main Saltlake
ii) Floating point
Example:
3.14
>>> type(3.14)
<class 'float'>
iii) Complex number
Example:
2+4j
>>> type(2+4j)
<class 'complex'>
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 2
Techno Main Saltlake
Strings
String is a group of characters.
To use a text in Python we have to use string.
In python, string can be used in two ways:
i) Using single Quotes (‘)
>>> 'hello'
'hello'
ii) Using double Quotes (“)
>>> "hello"
'hello'
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 3
Techno Main Saltlake
iii) Using triple Quotes (''')
We can specify multiline using triple quotes.
>>> ''' Welcome to the
family of
TECHNO INDIA '''
' Welcome to the\nfamily of\nTECHNO INDIA '
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 4
Techno Main Saltlake
>>> print('hello')
hello
>>> print("hello")
hello
>>> print(''' Techno
Main
Saltlake''')
Techno
Main
Saltlake
>>> print("Raja's PC")
Raja's PC
>>> print('abcd "xyz"')
abcd "xyz"
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 5
Techno Main Saltlake
String literal concatenation
Python concatenates two string literals that are placed side by side.
Example:
>>> print('abc' 'xyz')
abcxyz
>>> print("abc" "xyz")
abcxyz
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 6
Techno Main Saltlake
Unicode String
Unicode is a standard way of writing international text.
Python allows us to specify Unicode text by prefixing the string with u or U.
Example:
>>> u"ধন বাদ"
'ধন বাদ'
>>> U"ধন বাদ"
'ধন বাদ'
>>> print(u"ধন বাদ")
ধন বাদ
>>> print(U"ধন বাদ")
ধন বাদ
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 7
Techno Main Saltlake
Escape sequences
Some characters (like ‘, “”,\) connot be directly included into the string.
Such characters must be escaped by placing a backslash before them.
Example:
>>> print('Raja's PC')
SyntaxError: invalid syntax
>>> print('Raja\'s PC')
Raja's PC
>>> print("He says "I am Raja"")
SyntaxError: invalid syntax
>>> print("He says \"I am Raja\"")
He says "I am Raja"
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 8
Techno Main Saltlake
>>> print("abc \xyz")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
position 4-5: truncated \xXX escape
>>> print("abc \\xyz")
abc \xyz
We can use an escape sequence for the newline character (\n).
Example:
>>> print("aaa \n bbb \n ccc")
aaa
bbb
ccc
>>> print("aaa\nbbb\nccc")
aaa
bbb
ccc
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 9
Techno Main Saltlake
We can use an escape sequence (\t) to insert tab into the string.
Example:
>>> print("aaa\tbbb\tccc")
aaa bbb ccc
If a single backslash (\) at the end of the string is added, then it indicates that
the string is continued in the next line, but no new line is added.
Example:
>>> print("Welcome to \
Techno India")
Welcome to Techno India
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 10
Techno Main Saltlake
Raw Strings
To specify a string that should not handle any escape sequences and want to
display exactly as specified ; then the string should be specified as raw string.
Example:
>>> print(r"abc \n xyz's \t pqr")
abc \n xyz's \t pqr
>>> print(R"abc \n xyz's \t pqr")
abc \n xyz's \t pqr
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 11
Techno Main Saltlake
String formatting
The built-in function format() can be used to control the display of the string.
Example:
The string ‘hello’ is displayed as left-justified, right-justified, and center-
aligned in a field with 10 characters.
>>> format('hello','<10')
'hello '
>>> format('hello','>10')
' hello'
>>> format('hello','^10')
' hello '
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 12
Techno Main Saltlake
>>> format("hello","<10")
'hello ‘
>>> format("hello",">10")
' hello'
>>> format("hello","^10")
' hello '
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 13
Techno Main Saltlake
Data Type
Python supports 5 standard data types:
Number
String
List
Tuple
Dictionary
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 14
Techno Main Saltlake
Variables
Variables are reserved memory locations that store values.
For naming variables we should obey following rules:
i) The first character of an variable must be an underscore(‘_’) or letter (upper or
lower case).
ii) Rest of the character name can be underscore(‘_’), letter (upper or lower
case) and digits( 0 to 9).
iii) Variables are case sensitive
iv) Punctuation character (such as @ $ % ) are not allowed within variables.
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 15
Techno Main Saltlake
Prog. 1:
# Display data of different types using variables and literal constants
i=10
f=3.14
c=4+8j
msg="hello"
print("i=",i,"Datatype:",type(i))
print("f=",f,"Datatype:",type(f))
print("c=",c,"Datatype:",type(c))
print("msg=",msg,"Datatype:",type(msg))
Output:
i= 10 Datatype: <class 'int'>
f= 3.14 Datatype: <class 'float'>
c= (4+8j) Datatype: <class 'complex'>
msg= hello Datatype: <class 'str'>
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 16
Techno Main Saltlake
Prog. 2:
# Reassign values to a variable
x=10
print("x=",x,type(x))
x=3.14
print("x=",x,type(x))
x=4+8j
print("x=",x,type(x))
x="hello"
print("x=",x,type(x))
Output:
x= 10 <class 'int'>
x= 3.14 <class 'float'>
x= (4+8j) <class 'complex'>
x= hello <class 'str'>
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 17
Techno Main Saltlake
Multiple Assignments
In python we can assign single value to more than one variable
simultaneously.
Example
>>> a=b=c=d=0
>>> print("a=",a,"b=",b,"c=",c,"d=",d)
a= 0 b= 0 c= 0 d= 0
We can also assign different values to multiple variables simultaneously.
Example
>>> a,b,c,d=10,3.14,4+5j,"xyz"
>>> print("a=",a,"b=",b,"c=",c,"d=",d)
a= 10 b= 3.14 c= (4+5j) d= xyz Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 18
Techno Main Saltlake
Trying to reference a variable that has not been assigned any value causes an
error.
Example
>>> print(y)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
print(y)
NameError: name 'y' is not defined
>>> x=10
>>> print(x)
10
>>> del x
>>> print(x)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
print(x)
Dr. Shiladitya Chowdhury,
NameError: name 'x' is not defined
Assistant Professor, Dept. of MCA, 19
Techno Main Saltlake
Multiple statements on a single line
In python we can specify more than one statements in a single line using
semicolon (;).
Example
>>> s="abc" print(s)
SyntaxError: invalid syntax
>>> s="abc" ; print(s)
abc
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 20
Techno Main Saltlake
Boolean
Boolean is another data type in python.
A variable in boolean can have one of the two values- True or False
Example
>>> x=True
>>> x
True
>>> type(x)
<class 'bool'>
>>> x=False
>>> x
False
>>> 20==20
True
>>> 20==30
False
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 21
Techno Main Saltlake
Input operation
Prog.
# Read variables from user
name=input("Enter your Name:")
age=input("Enter your age:")
print("Your Name:",name,"Age:",age)
Output:
Enter your Name:Raja Roy
Enter your age:35
Your Name: Raja Roy Age: 35
Comments
Comments are the non-executable statements in a program.
In python, a hash sign (#) begins a comment.
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 22
Techno Main Saltlake
Keywords
Python programming language has following keywords:
>>> help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 23
Techno Main Saltlake
Operators
Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
// Floor Division
** Exponent
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 24
Techno Main Saltlake
>>> a=5
>>> b=3
>>> a+b
8
>>> a-b
2
>>> a*b
15
>>> a/b
1.6666666666666667
>>> a%b
2
>>> a//b
1
>>> a**b
125
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 25
Techno Main Saltlake
Comparison Operators
Operator Description
== Returns True if two values are exactly equal
!= Returns True if two values are not equal
> Returns True if value of the left side operand is
greater than value of the right side operand
>= Returns True if value of the left side operand is
greater than or equal to value of the right side
operand
< Returns True if value of the left side operand is less
than value of the right side operand
<= Returns True if value of the left side operand is less
than or equal to value of the right side operand
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 26
Techno Main Saltlake
>>> a=5
>>> b=3
>>> print(a==b)
False
>>> print(a!=b)
True
>>> print(a>b)
True
>>> print(a>=b)
True
>>> print(a<b)
False
>>> print(a<=b)
False
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 27
Techno Main Saltlake
Assignment Operators
Operator Description
= Assign value of the right side operand to the value of the
left side operand
+= Addition and assign
-= Subtraction and assign
*= Multiplication and assign
/= Division and assign
%= Modulus and assign
//= Floor Division and assign
**= Exponent and assign
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 28
Techno Main Saltlake
>>> a=10
>>> r=a
>>> r
10
>>> a=10
>>> b=7
>>> a+=b
>>> print("a=",a,"b=",b)
a= 17 b= 7
>>> a=10
>>> b=7
>>> a-=b
>>> print("a=",a,"b=",b)
a= 3 b= 7
>>> a=10
>>> b=7
>>> a*=b
>>> print("a=",a,"b=",b)
a= 70 b= 7 Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 29
Techno Main Saltlake
>>> a=10
>>> b=7
>>> a/=b
>>> print("a=",a,"b=",b)
a= 1.4285714285714286 b= 7
>>> a=10
>>> b=8
>>> a%=b
>>> print("a=",a,"b=",b)
a= 2 b= 8
>>> a=10
>>> b=4
>>> a//=b
>>> print("a=",a,"b=",b)
a= 2 b= 4
>>> a=2
>>> b=6
>>> a**=b
>>> print("a=",a,"b=",b) Dr. Shiladitya Chowdhury,
a= 64 b= 6 Assistant Professor, Dept. of MCA,
Techno Main Saltlake
30
Unary Operators
Unary operators act on single operands.
>>> a=11
>>> b=-a
>>> print(b)
-11
>>> print(a)
11
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 31
Techno Main Saltlake
Bitwise Operators
Bitwise AND (&)
Bitwise OR (|)
Bitwise XOR (^)
Bitwise NOT (~)
Left shift (<<)
Right shift (>>)
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 32
Techno Main Saltlake
a b Operator Result
3 5 & a&b 1
(00000011) (00000101) (00000001)
3 5 | a|b 7
(00000011) (00000101) (00000111)
3 5 ^ a^b 6
(00000011) (00000101) (00000110)
12 ~ ~a -13
(00001100) (11110011)
1 << a<<2 4
(00000001) (00000100)
10 >> a>>2 2
(00001010) (00000010)
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 33
Techno Main Saltlake
>>> a=3
>>> b=5
>>> a&b
1
>>> a|b
7
>>> a^b
6
>>> a=12
>>> ~a
-13
>>> a=1
>>> a<<2
4
>>> a=10
>>> a>>2
2 Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 34
Techno Main Saltlake
Logical Operators
Logical AND (and)
Logical OR (or)
Logical NOT (not)
Identity Operators
is Operator
Returns True if operands or values on both sides of the operator point to the
same object and False otherwise.
is not Operator
Returns True if operands or values on both sides of the operator point to the
different object and False otherwise.
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 35
Techno Main Saltlake
>>> a=10
>>> b=20
>>> c=10
>>> id(a)
1452423568
>>> id(b)
1452423728
>>> id(c)
1452423568
>>> a is b
False
>>> a is c
True
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 36
Techno Main Saltlake
>>> a is 10
True
>>> a is 20
False
>>> a is not b
True
>>> a is not c
False
>>> a is not 10
False
>>> a is not 20
True
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 37
Techno Main Saltlake
Membership Operators
in Operator
The operator returns True if a variable is found in the specified sequence and
False otherwise.
not in Operator
The operator returns True if a variable is not found in the specified sequence and
False otherwise.
>>> l=[10,20,30]
>>> 10 in l
True
>>> 15 in l
False
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 38
Techno Main Saltlake
>>> 10 not in l
False
>>> 15 not in l
True
>>> a=10
>>> b=12
>>> a in l
True
>>> b in l
False
>>> a not in l
False
>>> b not in l
True
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 39
Techno Main Saltlake
Operators precedence in python
The following table lists all operators from highest precedence to lowest.
Operator Description
** Exponentiation (raise to the power)
~ ,+ ,- Complement, unary plus and minus
* ,/, %, // Multiply, divide, modulo and floor division
+, - Addition and subtraction
>>, << Right and left bitwise shift
& Bitwise 'AND'
^ ,| Bitwise exclusive `OR' and regular `OR'
<= ,<, >, >= Comparison operators
<>, ==, != Equality operators
= ,%=, /=, //=, -=, +=, *=, **= Assignment operators
is, is not Identity operators
in, not in Membership operators
not, or, and Logical operators
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 40
Techno Main Saltlake
Operator precedence table is important as it affects how an expression is
evaluated.
Example:
>>> False==False or True
True
>>> False==(False or True)
False
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 41
Techno Main Saltlake
Operations on strings
Concatenation
>>> print("Techno "+"India")
Techno India
>>> print("10"+"20")
1020
>>> print("10"+20)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print("10"+20)
TypeError: can only concatenate str (not "int") to str
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 42
Techno Main Saltlake
Repetition
>>> print(5*"Abcd")
AbcdAbcdAbcdAbcdAbcd
>>> print("abcd"*3)
abcdabcdabcd
>>> print("abcd"*"3")
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
print("abcd"*"3")
TypeError: can't multiply sequence by non-int of type 'str'
>>> print("abcd"*3.0)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
print("abcd"*3.0)
TypeError: can't multiply sequence by non-int of type 'float'
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 43
Techno Main Saltlake
Slice a String
We can extract subsets of string by using the slice operator ( [ ] and [ : ] ).
The index of first character is 0 and the index of last character is n-1; where n
is the number of characters in the string.
>>> s="Techno Main Saltlake"
>>> print(s)
Techno Main Saltlake
>>> print(s[0])
T
>>> print(s[3:8])
hno M
>>> print(s[4:])
no Main Saltlake
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 44
Techno Main Saltlake
>>> print(s[:15])
Techno Main Sal
>>> print(len(s))
20
We can extract characters starting from the end of the string.
In this case, we have to specify the index as negative number.
>>> print(s[-1])
e
>>> print(s[-17:-2])
hno Main Saltla
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 45
Techno Main Saltlake
Other Data types
Lists
List consist of items separated by commas and enclosed within square brackets ( [ ] ).
The only difference in an array and list is that, array contains values of same data
type but the list can have values belonging to different types.
The index of first element of list is 0 and the index of last element is n-1; where n is
the total number of elements in the list.
We can perform the concatenation, repetition and slice operations on list.
>>> list1=['a','bc',10,3.14]
>>> list2=['d',75]
>>> print(list1)
['a', 'bc', 10, 3.14]
>>> print(list2)
['d', 75] Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 46
Techno Main Saltlake
>>> print(list1[0])
a
>>> print(list1[1])
bc
>>> print(list1[2])
10
>>> print(list1[3])
3.14
>>> print(list1[1:3])
['bc', 10]
>>> print(list1[2:])
[10, 3.14]
>>> print(list1 *2)
['a', 'bc', 10, 3.14, 'a', 'bc', 10, 3.14]
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 47
Techno Main Saltlake
>>> print(3*list1)
['a', 'bc', 10, 3.14, 'a', 'bc', 10, 3.14, 'a', 'bc', 10, 3.14]
>>> print(list1+list2)
['a', 'bc', 10, 3.14, 'd', 75]
>>> list1[0]='ABC'
>>> print(list1)
['ABC', 'bc', 10, 3.14]
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 48
Techno Main Saltlake
Tuples
Tuples consist of items separated by commas and enclosed within parenthesis.
It is very similar to list, but the main difference between lists and tuples is that we
can change the value in a list but that is not possible in tuple.
Tuple is a read only data type.
The index of first element of tuple is 0 and the index of last element is n-1; where
n is the total number of elements in the tuple.
We can perform the concatenation, repetition and slice operations on tuple.
>>> tup1=('A','XYZ',20,11.22)
>>> tup2=('P',77)
>>> print(tup1)
('A', 'XYZ', 20, 11.22)
>>> print(tup2)
('P', 77) Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 49
Techno Main Saltlake
>>> print(tup1[0])
A
>>> print(tup1[1])
XYZ
>>> print(tup1[2])
20
>>> print(tup1[3])
11.22
>>> print(tup1[1:3])
('XYZ', 20)
>>> print(tup1[2:])
(20, 11.22)
>>> print(2*tup2)
('P', 77, 'P', 77) Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 50
Techno Main Saltlake
>>> print(tup2*3)
('P', 77, 'P', 77, 'P', 77)
>>> print(tup1+tup2)
('A', 'XYZ', 20, 11.22, 'P', 77)
>>> tup1[0]='P'
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
tup1[0]='P'
TypeError: 'tuple' object does not support item assignment
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 51
Techno Main Saltlake
Dictionary
Python’s dictionaries stores data in key-value pairs.
The key-value pairs are enclosed with curly braces ({})
Each key-value pair is separated from other using a colon (:).
>>> d1={"A":1,"B":2,"C":3,"D":4}
>>> print(d1)
{'A': 1, 'B': 2, 'C': 3, 'D': 4}
>>> print(d1["B"])
2
>>> print(d1[1])
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
print(d1[1])
KeyError: 1 Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 52
Techno Main Saltlake
Functions of Type conversion
Some of the type conversion functions are as follows:
int(x) : Converts x to an integer
float(x) : Converts x to floating point number
str(x) : Converts x to a string
oct(x) : Converts x to an octal string
hex(x) : Converts x to a hexadecimal string
bin(x) : Converts x to a binary string
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 53
Techno Main Saltlake
>>> x="10"
>>> int(x)
10
>>> x=30
>>> float(x)
30.0
>>> str(x)
'30'
>>> x=12
>>> oct(x)
'0o14'
>>> hex(x)
'0xc'
>>> bin(x)
'0b1100' Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 54
Techno Main Saltlake