BDS306B_Module1
BDS306B_Module1
Introduction to Python
Elements of Python Language
Python block structure
Variables
Assignment statement
Data types in python
Operators
I/O functions (formatted and unformatted)
Introduction to Python
Python is an interpreted, high level and general purpose programming language. It was developed by
Guido Von Rossum (Netherlands). The design began in late 1990 and it was first released in February,
1991.
Features of Python
Token
Types of tokens
1. Variable
2. Data type
3. Literal
4. Constant
5. Operators
6. Keywords
7. Punctuators
8. Identifiers
Variable
Variable is a named memory location to store a value (number or character) that can change anywhere in
the program. Variables in python are dynamically typed – variable can be assigned a value without being
declared. Data type of a variable is determined automatically at the time of initialization.
id()
id function when used with variable gives address of memory location. Two or more variables storing
same integer value will be pointing to same memory location.
Example :
x = 23
y = 23
id(x) will be equal to id(y) as x and y storing same integer value. Once x or y value is changed
id(x) will not be equal to id(y)
Data type
Data type determines the type of value stored in a variable. There are two kinds of data types.
Primitive and non-primitive data types.
Primitive data types in python are int, float, bool, complex
Non-primitive data types are complex, str, list, tuple, set, etc. Non-primitive data types are also called as
collection data type.
Example :
x = 123
type(x)
output :
<class 'int'>
y = 123.4566
type(x)
output :
<class 'float'>
str1 = “python”
type(str1)
output :
<class 'str'>
c = 3 + 5j
type(c)
print(c.real)
print(c.imag)
output:
3.0
5.0
<class 'complex'>
x = True
type(x)
output :
<class 'bool'>
x = “a5$*ag”
type(x)
print(x[2]) # each character can be accessed using position(index) and hence ordered
x[3] = ‘z’ # error as string immutable and it cannot be changed
output:
<class 'str'>
$
Lists
Group of values of any data type enclosed in square brackets is called list. It is mutable and
ordered.
Example :
lst1 = [1,’a’,3.45]
type(lst1)
print(lst1[0]) # values in list can be accessed using position (index) and hence ordered
lst1[2] = ‘abc’ # as list is mutable, list can be modified
output :
<class 'list'>
1
Tuples
Group of values of any data type enclosed in braces is called tuple. It is immutable and ordered.
Example :
t1 = (1,5.6,”xyz”)
type(t1)
t1[1] = 34.5 # error as tuple is immutable and cannot be changed
output:
<class 'tuple'>
Byte data type is used to store group of integers in range 0-255. It immutable and ordered.
Example :
l st= [10,20,30]
b = bytes(lst)
type(b)
lst2 = bytes([10,20,456] )# error as only 0-255 can be stored in bytes
b[0] = 77 # error as bytes is immutable
for x in b :
print(x)
output:
<class 'bytes'>
10
20
30
Bytearray is same as byte except that bytearray is mutable
lst= [10,20,30]
b = bytearray(lst)
print(type(b))
lst2 =bytearray( [10,20,456] )# error as only 0-255 can be stored in bytes
b[0] = 77 # error as bytes is immutable
for x in b :
print(x)
output:
<class 'bytearray'>
77
20
30
Bytes and Bytearray is used to store image, audio and video files.
Dictionary
group of key value pair enclosed in flower bracket is called dictionary. Every value in dictionary
is key and value separated by “:”. It is mutable and unordered.
Rules :
1. In a dictionary, no two keys can be same.
2. data type of a key must be immutable
Example :
d1 = {'a':97, 'b':98,'c':99}
print(type(d1))
print(d1['b']) # values in dictionary is accessed using key and not position and hence
unordered
d1['c'] = 101 # values can be changed and keys can be added to dictionary and hence
# mutable
d1['d'] = 100
#d1[['e','f','g']]= [102,103,104] # error as key value must be immutable
output:
<class 'dict'>
98
Sets/Frozen sets
Set is group of value of any data types enclosed in flower brackets. It is mutable and
unordered. Duplicate values are not allowed in sets.
Example :
s1 = {1,2,3,5}
type(s1)
output:
<class 'set'>
Frozenset is same as set except that frozenset is immutable
To create frozenset :
s1 = frozenset({1,2,4,5})
type(s1)
output:
<class 'frozenset'>
lst = [10,20,30,40]
lst[0] is 10
lst[-1] is 40
lst[-2] is 30 # second item from right side
slicing - slicing is the process of extracted part of a sequence object.
Example :
lst = [10,20,30,40,50,60,70,80,90,100]
print(lst[0:5])
print(lst[5:])
print(lst[5:8])
print(lst[5:10:2])
print(lst[5::2])
print(lst[::-1])
print(lst[::-2])
print(lst[-3:])
print(lst[:-3])
Output :
[10, 20, 30, 40, 50]
[60, 70, 80, 90, 100]
[60, 70, 80]
[60, 80, 100]
[60, 80, 100]
[100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
[100, 80, 60, 40, 20]
[80, 90, 100]
[10, 20, 30, 40, 50, 60, 70]
concatenation - ‘+’ acts as concatenation operator when used with strings, lists and tuples
Example :
lst1 = [10,20]
lst2 = [30,40]
lst3 = lst1 + lst2
print(lst3)
str1 = “python”
str2 = “language”
str3 = str1 + str2
print(str3)
output :
[10, 20, 30, 40]
pythonlanguage
repetition - ‘*’ operator when used with strings, lists and tuples acts as repetition operators
Example :
lst1 = [10,20]
print(lst1 * 3)
str1 = "python"
print(lst1 * 4)
Exponent Float Literal – float value in exponent form is exponent float literal
234.5678 can be expressed as 23.45678e-01
String Literal
Single character or group of characters enclosed in single quote, double quote or triple quote is
called string literal. Triple quotes are used to store or assign multi line strings.
x = ‘a’
y = “a”
z = ‘’’a’’’
str1 = ‘Python’
str2 = “Language”
str3 = ‘’’Java’’’
Operators - Operators are symbols used to perform calculation, comparison and joining
expressions.
Parenthesis
Exponent
Division
Multiplication
Addition
Subtraction
Integer division operator (//) - used to extract only integer part after division and ignore decimal part
Example – 14//5 =2
Shift Operator (<<, >>) – used to shift binary numbers by 1 or more bits to the left or right
left shift – zeros will be added at he end
Example :
11010 << 2 = 1101000 ( 2 zeros are added)
11010 << 3 = 11010000 ( 3 zeros are added)
right shift – bits from end or right is ignored
11010 >> 2 = 110 ( last 2 bits ignored)
11010 >> 3 = 11 ( last 3 bits are ignored)
bitwise or (|) -
Truth Table for bitwise or
0|0=0
0|1=1
1|0=1
1|1=1
Example -
x = 10 ( 1010 in binary)
y = 12 ( 1100 in binary)
x | y = 1110 (using truth table)
x = 10 ( 1010 in binary)
y = 12 ( 1100 in binary)
x & y = 1000 (using truth table)
bitwise exclusive or (^) -
Truth Table for bitwise or
0^0=0
0^1=1
1^0=1
1^1=0
Example -
x = 10 ( 1010 in binary)
y = 12 ( 1100 in binary)
x ^ y = 0110 (using truth table)
bitwise complement (~) - is unary operator
Example -
x = 12
~x = -(x+1) = -(12+1) = -13
Membership operator (in, not in)– used to check if a value exists in sequence object (list, tuple, string,
etc)
str1 = “python”
“p” in str1 returns True
“p” not in str1 returns False
Identity operator (is, is not) – used to check if variables are pointing to same object or same memory
location
x = y = 12
x is y returns True
x is not y returns False
z = 14
x is z returns False
Keywords – Words that have meaning in a programming language are called keywords or reserved
words.
Example - for, else, if, etc are keywords
xyz, num, n1, etc. are not keywords
Comments in Python
Comments are lines in program that are ignored by compiler or interpreter. They are used for
documentation purpose.
Single line comment - ‘#’ symbol is used for single line comments
Multiple line comments – triple quotes ‘’’ are used to enclose multiple line comments
I/O Functions
Input Function – accepting input from user at run time is done using input() function.
input() function returns value of string type. It needs to be converted to
required type while accepting input.
eval() - function that can be used with input() function. It determines and converts the user
input to int, float, string or complex.
print Function – used to display output on screen. To display strings single, double or triple quotes
can be used.
Syntax
print(argument)
Example -
x = 10
y = 20
print(“x = “,x,”y=”,y)
output –
x = 10y= 20
Escape sequence (\n, etc) can be used for print in the print statements
Example - print(‘Hello’)
To print Joyce’s car - we need to use double quote
print(“Joyce’s car”)
sep flag – sep flag is used in print statement to specify the character to be used
instead of space to separate the arguments while displaying.
Example -
print(“a”,”b”,”c”,sep=”*”)
output – a*b*c
end flag – end flag is used in print statement to specify the character to be used
instead of newline to separate ouput of two print statements. By default end flag is set to
newline.
Example -
print(“Python”)
print(“for”)
print(“Data Science”)
output – Python
for
Data Science
Example -
print(“Python”, end=”$”)
print(“for”, end = “$”
print(“Data Science”)
print(“Semester III”)
output - Python$for$Data Science
Semester III
Example :
name = “Virat”
USN = 123
print(f’name = {name}, USN = {USN}’)
using format specifier
name = “Virat”
USN = 123
perc = 78.3456
print(‘name = %s, USN = %d, Percentage=%.2f’%(name,USN,perc))