Python Programming
B ABURAJ M.
Assistant Professor
Government Engineering College Kozhikode
February 29, 2020
Overview
Introduction
The Basics
Keywords
Variables
The Input/Output Statements
Operators
Decision Making
Iterative Statements
The while Loop
The for Loop
Arrays
The List
The Tuple
The Set
The Dictionary
The String
February 29, 2020 Python Programming 0
Introduction
Introduction
February 29, 2020 Python Programming 1
Syllabus
Object oriented programming
Object oriented programming
I Introduction to Python: Comparison of Python constructs with C
I Keywords
I Variables
I Operators
I Expression and Statements
I Control Statements
I Programming Examples
I Comparison of constructs of python with C
I Functions
I Calling Functions
I User Defined Functions
I Strings and Lists
I Programming Examples
I Basics of Tuples
I Dictionary
I Exception handling in python
February 29, 2020 Python Programming 2
Python Interactive Terminal
Introduction
Running Python Program
I Type python from OS terminal to launch python interactive terminal.
Python Interactive Terminal
Figure: Python Interactive Terminal
February 29, 2020 Python Programming 3
Python Interactive Terminal
Introduction
Running Simple Program
I Sum of two numbers
Running a Simple Program in Interactive Terminal
Figure: Python Interactive Terminal in Action
February 29, 2020 Python Programming 4
Running Python Script
Introduction
Executing Python Script
I Create a file pg1.py in any text editor and enter following commands into
it.
x=3
y=5
z=x+y
print(z)
I To execute the program, type the following command in the OS terminal,
python pg1.py
8
February 29, 2020 Python Programming 5
Python Features
Introduction
I Interpreted Language: Python is processed at runtime by Python Inter-
preter.
I Object-Oriented Language: It supports object-oriented features and tech-
niques of programming.
I Interactive Programming Language: Users can interact with the python
interpreter directly for writing programs.
I Easy language: Python is easy to learn language especially for beginners.
I Straightforward Syntax: The formation of python syntax is simple and
straightforward which also makes it popular.
I Easy to read: Python source-code is clearly defined and visible to the eyes.
I Portable: Python codes can be run on a wide variety of hardware platforms
having the same interface.
I Extendable: Users can add low level-modules to Python interpreter.
I Scalable: Python provides an improved structure for supporting large pro-
grams then shell-scripts.
February 29, 2020 Python Programming 6
Python Limitations
Introduction
I Speed: Python is slower than C or C++. But of course, Python is a high-
level language, unlike C or C++ it’s not closer to hardware.
I Mobile Development: Python is not a very good language for mobile de-
velopment . It is seen as a weak language for mobile computing.
I Memory Consumption: Python is not a good choice for memory intensive
tasks. Due to the flexibility of the data-types, Python’s memory consump-
tion is also high.
February 29, 2020 Python Programming 7
The Basics
The Basics
February 29, 2020 Python Programming 8
First Program
Python Programming Example
1 #First Python Program
2 print("Hello World!")
February 29, 2020 Python Programming 9
First Program
Python Programming Example - Output
1 Hello World!
February 29, 2020 Python Programming 10
Comments in Python
The Basics
I In Python, there are two types of comments–one is a single-line comment
and the other is multiline comment.
I For a single-line comment, # is used, while for a multiline comment, triple
quotes """ are used:
I #This is a single line comment in Python
I """ For multi-line
comment use three
double quotes"""
February 29, 2020 Python Programming 11
Keywords
Keywords
February 29, 2020 Python Programming 12
Keywords
The Basics
I Python has a set of keywords that are reserved words that cannot be used
as variable names, function names, or any other identifiers:
and del from not while
as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try
February 29, 2020 Python Programming 13
Variables
Variables
February 29, 2020 Python Programming 14
Variables
Variables
I Variables are containers for storing data values.
I Unlike other programming languages, Python has no command for declar-
ing a variable.
I A variable is created the moment you first assign a value to it.
I Examples
I x=10
I current=2.4554
I charge=1E-16 # charge of electron
I firstLetter=’A’
I msg="PYTHON"
I sentence=’This is a string’
February 29, 2020 Python Programming 15
Variables - Naming Convention
Variables
I Reserved key words such as if , else , and so on cannot be used for naming
variables.
I Variable names can begin with _ , $ , or a letter.
I Variable names can be in lower case and uppercase.
I Variable names cannot start with a number.
I White space characters are not allowed in the naming of a variable.
February 29, 2020 Python Programming 16
Variables - Classes
The Basics
I NoneType - Nothing.
I int - Integer.
I bool - boolean (True, False).
I float - Effectively a 64 bit floating point number on a 64 bit system.
I complex - A pair of floats - complex number.
I string - A continuous ordered collection of characters.
I list - An ordered heterogeneous collection of objects.
I set - An unordered heterogeneous collection of unique objects.
I dict - A Dictionary (A key, value pair mapping).
I tuple - An immutable ordered heterogeneous collection of objects.
February 29, 2020 Python Programming 17
Variables - Classes
Variables
Type Example
NoneType x=None
int x=10
bool x=True
float x=3.1415
complex x=3+4j
string x=’Welcome’
list x=[1,1,2,2,3,3]
set x={1,2,3}
dict x={’a’:1,’b’:1,’c’:1}
tuple x=(1,2,3)
February 29, 2020 Python Programming 18
Type Conversion
Variables
I type(variable) - Gives the type of the variable.
I To convert one variable type to another
I int(variable) - Convert variable to integer.
I float(variable) - Convert variable to float type.
I str(variable) - Convert variable to string.
February 29, 2020 Python Programming 19
Variable Types
Python Programming Example
1 # Variable type example
2 x=10
3 y=2.5
4 msg=’This is a string’
5 print(type(x))
6 print(type(y))
7 print(type(msg))
February 29, 2020 Python Programming 20
Variable Types
Python Programming Example - Output
1 <type ’int’>
2 <type ’float’>
3 <type ’str’>
February 29, 2020 Python Programming 21
Variable Type Conversion
Python Programming Example
1 # Type converstion example
2 x=’10’
3 print(type(x))
4 w=int(x)
5 z=str(x)
6 s=float(x)
7 print(type(w),’, ’,type(z),’, ’,type(s))
8 print(w,’, ’,z,’, ’,s)
February 29, 2020 Python Programming 22
Variable Type Conversion
Python Programming Example - Output
1 <type ’str’>
2 (<type ’int’>, ’, ’, <type ’str’>, ’, ’, <type ’float’>)
3 (10, ’, ’, ’10’, ’, ’, 10.0)
February 29, 2020 Python Programming 23
The Input/Output Statements
The Input/Output Statements
February 29, 2020 Python Programming 24
The print() & input()
Input / Output Statements
I print(arguments) - Displays results in standard output device.
I input(prompt string) - Reads data from standard input device after
displaying prompt string.
I An appropriate type conversion is required after input(), if the data being
processed is of the type numeric type.
I Examples
I print(x)
I print(x,y,z)
I x=input(’Enter value for x’)
I y=int( input(’Enter value for x’) )
February 29, 2020 Python Programming 25
The input() Illustration
Input / Output Statements
Figure: Python Reading from Keyboard
February 29, 2020 Python Programming 26
The print()
Python Programming Example
1 # Print example
2 x=5
3 y=10.123456
4 z=’abc’
5 print(x,y,z)
6 print(’x=%d, y=%f, z=%s’ %(x,y,z))
7 print(’x={}, y={}, z={}’.format(x,y,z))
8 print(’x={0}, y={1}, z={2}’.format(x,y,z))
9 print(’x=’ + str(x) + ’, y=’ + str(y) + ’, z=’ + z)
February 29, 2020 Python Programming 27
The print()
Python Programming Example - Output
1 (5, 10.123456, ’abc’)
2 x=5, y=10.123456, z=abc
3 x=5, y=10.123456, z=abc
4 x=5, y=10.123456, z=abc
5 x=5, y=10.123456, z=abc
February 29, 2020 Python Programming 28
Operators
Operators
February 29, 2020 Python Programming 29
Arithmetic Operators
Operators
Operator Description Example (x=20, y=3) Result
+ Addition x + y 23
- Subtraction x - y 17
* Multiplication x * y 60
/ Float division x / y 6.66667
% Reminder after division x % y 2
** Exponentiation x ** y 8000
// Integer division x // y 6
February 29, 2020 Python Programming 30
Assignment Operators
Operators
Operator Description Example (x=5) Result
= x = 5 x = 5 5
+= x += 3 x = x + 3 8
-= x -= 3 x = x - 3 2
*= x *= 3 x = x * 3 15
/= x /= 3 x = x / 3 1.6666
%= x %= 3 x = x % 3 2
//= x //= 3 x = x // 3 1
**= x **= 3 x = x ** 3 125
&= x &= 3 x = x & 3 1
|= x |= 3 x = x | 3 7
ˆ= x ˆ= 3 x = x ˆ 3 6
>>= x >>= 3 x = x >> 3 0
<<= x <<= 3 x = x << 3 40
February 29, 2020 Python Programming 31
Comparison Operators
Operators
Operator Description Example (x=20,y=3) Result
== Equal x == y False
!= Not equal x != y True
> Greater than x > y True
< Less than x < y False
>= Greater than or equal to x >= y True
<= Less than or equal to x <= y False
February 29, 2020 Python Programming 32
Logical Operators
Operators
Operator Description Example (x=5, y=9) Result
Returns True if both
and x < 5 and x < 10 False
statements are true
Returns True if one of the
or x < 5 or x < 4 True
statements is true
Reverse the result,
not returns False if the not(x < 5 and x < 10) True
result is true
February 29, 2020 Python Programming 33
Identity Operators
Operators
Operator Description Example (x=(1,2)) Result
Returns true if both
is variables are the same x is y
object
Returns true if both
is not variables are not the same x is not y
object
February 29, 2020 Python Programming 34
Membership Operators
Operators
Operator Description Example (x=5 and y=9) Result
Returns True if a sequence
in with the specified value x in y
is present in the object
Returns True if a sequence
with the specified value
not in x not in y
is not present in the
object
February 29, 2020 Python Programming 35
Bitwise Operators
Operators
Operator Name Description Example
Sets each bit to 1 if both
& AND x & y
bits are 1
Sets each bit to 1 if one
| OR x | y
of two bits is 1
Sets each bit to 1 if only
ˆ XOR x ˆ y
one of two bits is 1
~ NOT Inverts all the bits x ~ y
Shift left by pushing
Zero fill zeros in from the right
<< x << y
left shift and let the leftmost bits
fall off
Shift right by pushing
Signed copies of the leftmost bit
>> right in from the left, and let x >> y
shift the rightmost bits fall
off
February 29, 2020 Python Programming 36
Decision Making
Decision Making
February 29, 2020 Python Programming 37
if Statement
The Basics
I Decision making is required when we want to execute a code only if a
certain condition is satisfied.
if test expression:
statement(s)
I Example:
if x>0:
print(’The value is positive’)
February 29, 2020 Python Programming 38
if. . . else Statement
Decision Making
I The if..else statement evaluates test expression and will execute body of if
only when test condition is True. If the condition is False, body of else is
executed. Indentation is used to separate the blocks.
if test expression:
statement(s)
else:
statement(s)
I Example:
if x>0:
print(’The value is positive’)
else:
print(’The value is negative or zero’)
February 29, 2020 Python Programming 39
if. . . elif. . . else Statement
Decision Making
I The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block
and so on. If all the conditions are False, body of else is executed.
if test expression:
statement(s)
elif test expression:
statement(s)
else:
statement(s)
I Example:
if x>0:
print(The value is positive’)
elif x<0:
print(’The value is neative’)
else:
print(’The value is zero’)
February 29, 2020 Python Programming 40
Nested if statement
Decision Making
I We can have a if...elif...else statement inside another if...elif...else statement.
This is called nesting in computer programming.
I Example:
1 num = float(input("Enter a number: "))
2 if num >= 0:
3 if num == 0:
4 print("Zero")
5 else:
6 print("Positive number")
7 else:
8 print("Negative number")
9 }
February 29, 2020 Python Programming 41
Exercise
Decision Making
I Predict the output:
1 if 2 == 2:
2 print("ice cream is tasty!")
February 29, 2020 Python Programming 42
Exercise 1
Decision Making
I Predict the output:
1 if "cat" == "dog":
2 print("prrrr")
3 else:
4 print("ruff")
February 29, 2020 Python Programming 43
Exercise 2
Decision Making
I Predict the output:
1 if 5 > 10:
2 print("fan")
3 elif 8 != 9:
4 print("glass")
5 else:
6 print("cream")
February 29, 2020 Python Programming 44
Exercise 3
Decision Making
I Predict the output:
1 name = "maria"
2 if name == "melissa":
3 print("usa")
4 elif name == "mary":
5 print("ireland")
6 else:
7 print("colombia")
February 29, 2020 Python Programming 45
Exercise 4
Decision Making
I Predict the output:
1 if 88 > 100:
2 print("cardio")
February 29, 2020 Python Programming 46
Exercise 5
Decision Making
I Predict the output:
1 hair_color = "blue"
2 if 3 > 2:
3 if hair_color == "black":
4 print("You rock!")
5 else:
6 print("Boring")
February 29, 2020 Python Programming 47
Exercise 6
Decision Making
I Predict the output:
1 if True:
2 print(101)
3 else:
4 print(202)
February 29, 2020 Python Programming 48
Exercise 7
Decision Making
I Predict the output:
1 if False:
2 print("Nissan")
3 elif True:
4 print("Ford")
5 elif True:
6 print("BMW")
7 else:
8 print("Audi")
February 29, 2020 Python Programming 49
Exercise 8
Decision Making
I Predict the output:
1 if 1:
2 print("1 is truthy!")
3 else:
4 print("???")
February 29, 2020 Python Programming 50
Exercise 9
Decision Making
I Predict the output:
1 if 0:
2 print("huh?")
3 else:
4 print("0 is falsy!")
February 29, 2020 Python Programming 51
Exercise 10
Decision Making
I Predict the output:
1
2 a = True
3 b = False
4 c = False
5
6 if not a or b:
7 print 1
8 elif not a or not b and c:
9 print 2
10 elif not a or b or not b and a:
11 print 3
12 else:
13 print 4
February 29, 2020 Python Programming 52
Iterative Statements
Iterative Statements
February 29, 2020 Python Programming 53
The while Loop
The while Loop
February 29, 2020 Python Programming 54
Iterative Statements
Iterative Statements
I Iteration statements or loop statements allow us to execute a block of
statements as long as the condition is true.
I Loops statements are used when we need to run same code again and
again, each time with a different value.
February 29, 2020 Python Programming 55
The while loop
Iterative Statements
I A while loop statement repeatedly executes a target statement as long as
a given condition is true.
I Syntax:
1 while expression:
2 statement(s)
I Example:
1 >>> i = 1
2 >>> while i < 5:
3 print(i)
4 i += 1
5 1
6 2
7 3
8 4
9 5
February 29, 2020 Python Programming 56
The while - else loop
Iterative Statements
I The else part is executed if the condition in the while loop evaluates to
False.
I The while loop can be terminated with a break statement. In such case,
the else part is ignored.
I Syntax:
1 while expression:
2 statement(s)
3 else:
4 statement(s)
I Example:
1 >>> i = 1
2 >>> while i < 5:
3 print(i)
4 i += 1
5 else:
6 print(’The i>=5’)
February 29, 2020 Python Programming 57
Exercise 1
Iterative Statements
I Predict the output:
1 while False:
2 print(’Hello’)
February 29, 2020 Python Programming 58
Exercise 2
Iterative Statements
I Predict the output:
1 while True:
2 print(’Hello’)
February 29, 2020 Python Programming 59
Exercise 3
Iterative Statements
I Predict the output:
1 i=1
2 while i<5:
3 print(i)
4 i+=1
February 29, 2020 Python Programming 60
Exercise 4
Iterative Statements
I Predict the output:
1 i=10
2 while i>5:
3 print(i)
4 i-=1
February 29, 2020 Python Programming 61
Exercise 5
Iterative Statements
I Predict the output:
1 i=10
2 while i<5:
3 print(i)
4 i-=1
February 29, 2020 Python Programming 62
Exercise 6
Iterative Statements
I Predict the output:
1 i=5
2 while i>5:
3 print(i)
4 i-=1
February 29, 2020 Python Programming 63
Exercise 7
Iterative Statements
I Predict the output:
1 x=0
2 while x<5
February 29, 2020 Python Programming 64
While loop example
Python Programming Example
1 # Reverse of the given number
2 num=int(input(’Enter the number: ’))
3 n=num
4 rev=0
5 while n>0:
6 digit=n%10
7 rev = rev *10 + digit
8 n=n//10
9 print(’Reverse of’,num, ’is ’,rev)
February 29, 2020 Python Programming 65
break, continue, pass statement
Iterative Statements
I break: Terminates the loop statement and transfers execution to the state-
ment immediately following the loop.
I continue: Causes the loop to skip the remainder of its body and immedi-
ately retest its condition prior to reiterating.
I pass: The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to execute.
February 29, 2020 Python Programming 66
Exercise 8
Iterative Statements
I Predict the output:
1 x=0
2 while x<10:
3 x=x+1
4 if x>5:
5 break
6 print(x)
February 29, 2020 Python Programming 67
Exercise 9
Iterative Statements
I Predict the output:
1 x=10
2 while x>1:
3 x=x-1
4 if x<4:
5 break
6 print(x)
February 29, 2020 Python Programming 68
Exercise 10
Iterative Statements
I Predict the output:
1 x=0
2 while x<=10:
3 x=x+1
4 if x>4:
5 continue
6 print(x)
February 29, 2020 Python Programming 69
Exercise 11
Iterative Statements
I Predict the output:
1 x=0
2 while x<=20:
3 x=x+1
4 if x>=4 and x<=8:
5 continue
6 print(x)
February 29, 2020 Python Programming 70
Exercise 12
Iterative Statements
I Predict the output:
1 x=10
2 while x>0:
3 #Comment is not enough
February 29, 2020 Python Programming 71
Exercise 13
Iterative Statements
I Predict the output:
1 x=10
2 while x>0:
3 pass
February 29, 2020 Python Programming 72
Exercise 13
Iterative Statements
I Predict the output:
1 x=1
2 c=1
3 while x<=10:
4 x=x+1
5 if x%2==0:
6 pass
7 else:
8 c+=1
9 print(c)
February 29, 2020 Python Programming 73
The range()
Iterative Statements
I The range() function returns a sequence of numbers, starting from 0 by
default, and increments by 1 (by default), and ends at a specified number.
I range(start, stop, step)
I start: Optional. An integer number specifying at which position to start.
Default is 0
I stop: Required. An integer number specifying at which position to end.
I step: Optional. An integer number specifying the incrementation. Default is 1
I Example:
1 >>> range(5)
2 [0, 1, 2, 3, 4]
3 >>> range(2,5)
4 [2, 3, 4]
5 >>> range(1,5,2)
6 [1,3]
7 >>> range(5,0,-1)
8 [5,4,2,3,1]
9 >>> range(0,5,-1)
10 [ ]
February 29, 2020 Python Programming 74
The for Loop
The for Loop
February 29, 2020 Python Programming 75
The for loop
Iterative Statements
I A for loop is used for iterating over a sequence, that is either a list, a tuple,
a dictionary, a set, or a string.
I Syntax:
1 for iterating_variable in sequence:
2 statements(s)
I Example:
1 >>>for x in range(5):
2 print(x)
3
4 0
5 1
6 2
7 3
8 4
February 29, 2020 Python Programming 76
Exercise 14
Iterative Statements
I Predict the output:
1 for x in range(2, 6):
2 print(x)
February 29, 2020 Python Programming 77
Exercise 15
Iterative Statements
I Predict the output:
1 for x in range(2,6,2):
2 print(x)
February 29, 2020 Python Programming 78
Exercise 16
Iterative Statements
I Predict the output:
1 for x in range(2,6,2):
2 print(x)
February 29, 2020 Python Programming 79
Exercise 16
Iterative Statements
I Predict the output:
1 for x in range(2,6,-1):
2 print(x)
February 29, 2020 Python Programming 80
Exercise 16
Iterative Statements
I Predict the output:
1 for x in range(6,2,-1):
2 print(x)
February 29, 2020 Python Programming 81
Exercise 16
Iterative Statements
I Predict the output:
1 msg=’PYTHON’
2 for i in range(0,6):
3 print(msg[i])
February 29, 2020 Python Programming 82
Exercise 16
Iterative Statements
I Predict the output:
1 msg=’PYTHON’
2 for i in range(0,7):
3 print(msg[i])
February 29, 2020 Python Programming 83
Exercise 16
Iterative Statements
I Predict the output:
1 msg=’PYTHON’
2 for x in msg:
3 print(x)
February 29, 2020 Python Programming 84
Exercise 17
Iterative Statements
I Predict the output:
1 msg=’PYTHON’
2 for x in msg:
3 print(x)
February 29, 2020 Python Programming 85
Exercise 18
Iterative Statements
I Predict the output:
1 n=[1,2,3,4,5]
2 for x in n:
3 print(x)
February 29, 2020 Python Programming 86
Exercise 19
Iterative Statements
I Predict the output:
1 n=range(10)
2 for x in n:
3 print(x)
February 29, 2020 Python Programming 87
Exercise 20
Iterative Statements
I Predict the output:
1 n=range(1,11,2)
2 for x in n:
3 print(x)
February 29, 2020 Python Programming 88
Exercise 21
Iterative Statements
I Predict the output:
1 for x in range(10):
2 print(x)
3 if x>5:
4 break
February 29, 2020 Python Programming 89
Exercise 22
Iterative Statements
I Predict the output:
1 for x in range(10):
2 if x>5:
3 continue
4 print(x)
February 29, 2020 Python Programming 90
Exercise 23
Iterative Statements
I Predict the output:
1 for x in range(10):
2 pass
3 print(x)
February 29, 2020 Python Programming 91
For loop example
Python Programming Example
1 # Sum of odd numbers using for loop
2 limit=int(input(’Enter the limit: ’))
3 sum=0
4 for n in range(1,limit+1,2):
5 sum=sum+n
6 print(’Sum of first ’,limit, ’ odd numebers is ’,sum)
February 29, 2020 Python Programming 92
For loop example
Python Programming Example
1 # Occurance of character ’A’ in the message string
2 msg=input(’Enter the message string: ’)
3 count=0
4 for char in msg:
5 if char==’A’ or char==’a’:
6 count=count+1
7 print(’Occurance of a in "’,msg,’" is ’, count)
February 29, 2020 Python Programming 93
The for - else loop
Iterative Statements
I A for loop can have an optional else block as well. The else part is executed
if the items in the sequence used in for loop exhausts.
I break statement can be used to stop a for loop. In such case, the else part
is ignored.
I Example:
1 digits = [0, 1, 5]
2 for i in digits:
3 print(i)
4 else:
5 print("No items left.")
I Output:
1 0
2 1
3 5
4 No items left.
February 29, 2020 Python Programming 94
For loop example
Python Programming Example
1 import math
2 A=10
3 F=100
4 Fs=1000
5 import time
6 for x in range(500):
7 V=A+int(math.sin(2*math.pi*F/Fs*x)*A)
8 #V=int(10*math.exp(x/20.0))
9 for y in range(V+1):
10 print(’*’,end=""),
11 time.sleep(.15)
12 print(’\n’)
February 29, 2020 Python Programming 95
Prime Number Check
Python Programming Example
1 # Check the given number is prime or not
2 from math import sqrt
3 N=int(input(’Input number:’))
4 L=int(sqrt(N))+1
5 isprime=True
6 for n in range(2,L):
7 if N%n==0:
8 isprime=False
9 break
10 if isprime:
11 print(’The number’,N,’is prime’)
12 else:
13 print(’The number’,N,’is not prime’)
February 29, 2020 Python Programming 96
Programming Exercise
Questions
1. Generate Fibonacci series upto N.
2. Generate Prime numbers upto N.
3. Find largest/smallest among a set.
4. Sort the set in ascending/descending order.
5. Generate Armstrong numbers upto N.
6. Find factorial of a number.
7. Find GCD of two numbers.
8. Count vowels in a string.
9. Compute ex
10. Compute sin(x)
11. Find difference between two dates.
February 29, 2020 Python Programming 97
Arrays
Arrays
February 29, 2020 Python Programming 98
Python Collections (Arrays)
Arrays
I There are four collection data types in the Python programming language:
I List is a collection which is ordered and changeable. Allows duplicate mem-
bers.
I Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
I Set is a collection which is unordered and unindexed. No duplicate members.
I Dictionary is a collection which is unordered, changeable and indexed. No
duplicate members.
I Example:
1 >>> sample_list = [’apple’, ’banana’, ’cherry’]
2 >>> sample_tuple = (’apple’, ’banana’, ’cherry’)
3 >>> sample_set = {’apple’, ’banana’, ’cherry’}
4 >>> sample_dict = {’brand’: ’Ford’, ’model’: ’Mustang’, ’year’: 1964}
February 29, 2020 Python Programming 99
References or Aliases of Collections (Arrays) in Python
Arrays
I Suppose A is a Python array.
I When we try to assign variable B to A, then B is not a new variable.
I Instead B is a new reference/alias name to variable A.
I Both A and B refers to same object.
I All the modification done to B will be reflected on A.
I Example:
1 >>> A=[1,2,3]
2 >>> # New reference to list B
3 >>> B=A
4 >>> print(A)
5 [1, 2, 3]
6 >>> # Modify last item of B.
7 >>> B[2]=5
8 >>> # A also will be modified
9 >>> print(A)
10 [1, 2, 5]
February 29, 2020 Python Programming 100
The List
The List
February 29, 2020 Python Programming 101
List
Arrays
I List is a collection which is ordered and changeable.
I Allows duplicate members.
I In Python tuples are written with square brackets [].
I The range() generates a list.
I Example:
1 B=[] # Creates an empty list
2 A=[1,2,3,4,5,6,7,8]
3 C=range(5) # Generates a list containing numbers from 0 to 4
I Initialize list with for loop.
1 >>> C=[0 for x in range(10)] # List filled with ten zeros.
2 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
3 >>> D=[1.5 for x in range(10)] # List filled with ten 1.5s.
4 [1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5]
5 >>> E=[’HELLO’ for x in range(5)] # List filled with five ’HELLO’.
6 [’HELLO’, ’HELLO’, ’HELLO’, ’HELLO’, ’HELLO’]
7 >>> F=[[1,2,3] for x in range(5)] # List filled with five [1,2,3]
8 [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
February 29, 2020 Python Programming 102
Lists - Indexing
Arrays
I Access the list items by referring to the index number
I Negative indexing means beginning from the end, -1 refers to the last item,
-2 refers to the second last item etc.
I You can specify a range of indexes by specifying where to start and where
to end the range. When specifying a range, the return value will be a new
list with the specified items.
I Example:
1 B=[] # Creates an empty list
2 A=[1,2,3,4,5,6,7,8]
3 print(A[1]) # Prints second item
4 print(A[-1]) # Prints last item
5 print(A[0]) # prints first item
6 print(A[2:5]) # prints third, fourth and fifth items
7 print(A[:4]) # prints all elements from beginning to fourth
8 print(A[5:]) # prints all elements from fifth to end
9 print(A[-4:-1]) # print items from index -4 (included) to index -1 (excluded)
February 29, 2020 Python Programming 103
List - Indexing
Arrays
1 >>> B=[] # Creates an empty list
2 >>> A=[1,2,3,4,5,6,7,8]
3 >>> print(A[1]) # Prints second item
4 >>> print(A[-1]) # Prints last item
5 >>> print(A[0]) # prints first item
6 >>> print(A[2:5]) # prints third, fourth and fifth items
7 >>> print(A[:4]) # prints all elements from beginning to fourth
8 >>> print(A[5:]) # prints all elements from fifth to end
9 >>> print(A[-4:-1]) # print items from index -4 (included) to index -1 (
excluded)
I Output:
1
2
3 >>> 2
4 >>> 8
5 >>> 1
6 >>> [3, 4, 5]
7 >>> [1, 2, 3, 4]
8 >>> [6, 7, 8]
9 >>> [5, 6, 7]
February 29, 2020 Python Programming 104
List - Change Item Value
Arrays
I To change the value of a specific item, refer to the index number
I Example:
1 >>> A=[1,2,3,4,5]
2 >>> A[2]=10
3 >>> print(A)
I Output:
1 >>>
2 >>> A=[1,2,10,4,5]
February 29, 2020 Python Programming 105
List - Loop Through a List
Arrays
I You can loop through the list items by using a for loop:
I Example:
1 fruits = [’apple’, ’banana’, ’cherry’]
2 for x in fruits:
3 print(x)
4
5 A = [1,2,3,4,5]
6 for x in A:
7 print(x)
8
9 B = [1,’banana’,3.45,4+2j,-5]
10 for x in B:
11 print(x)
February 29, 2020 Python Programming 106
List - Check if Item Exists
Arrays
I To determine if a specified item is present in a list use the in keyword:
I Example:
1 fruits = [’apple’, ’banana’, ’cherry’]
2 if ’apple’ in fruits:
3 print(’Yes, apple is in the fruits list’)
February 29, 2020 Python Programming 107
List - List Length
Arrays
I To determine how many items a list has, use the len() function:
I Example:
1 >>> fruits = [’apple’, ’banana’, ’cherry’]
2 >>> print(len(fruits))
I Output:
1 >>
2 >>> 3
February 29, 2020 Python Programming 108
List - Add Items
Arrays
I To add an item to the end of the list, use the append() method
I To add an item at the specified index, use the insert() method:
I Example:
1 >>> fruits = [’apple’, ’banana’, ’cherry’]
2 >>> fruits.append(’orange’)
3 >>> print(fruits)
4 >>> fruits.insert(2, ’pineapple’)
5 >>> print(fruits)
I Output:
1 >>>
2 >>>
3 >>> [’apple’, ’banana’, ’cherry’, ’orange’]
4 >>>
5 >>> [’apple’, ’banana’, ’pineapple’, ’cherry’, ’orange’]
February 29, 2020 Python Programming 109
List - Remove Item
Arrays
I The remove() method removes the specified item:
I The pop() method removes the specified index, (or the last item if index
is not specified):
I Example:
1 >>> fruits = [’apple’, ’banana’, ’cherry’]
2 >>> fruits.remove(’banana’)
3 >>> print(fruits)
4 >>> fruits.pop()
5 >>> print(fruits)
I Output:
1 >>
2 >>
3 >> [’apple’, ’cherry’]
4 >>
5 >> [’apple’]
February 29, 2020 Python Programming 110
List - Deletes Items or List
Arrays
I The del keyword removes the specified index:
I The del keyword can also delete the list completely:
I The clear() method empties the list:
I Example:
1 fruits = [’apple’, ’banana’, ’cherry’]
2 del fruits[0]
3 print(fruits)
4
5 fruits = [’apple’, ’banana’, ’cherry’]
6 del fruits
7 print(fruits) # Creates error - variable fruits does not exists
8
9 fruits = [’apple’, ’banana’, ’cherry’]
10 fruits.clear()
11 print(fruits)
February 29, 2020 Python Programming 111
List - Copy a List
Arrays
I You cannot copy a list simply by typing list2 = list1, because: list2 will
only be a reference to list1, and changes made in l list1 will automatically
also be made in list2.
I There are ways to make a copy, one way is to use the built-in List method
copy().
I Another way to make a copy is to use the built-in method list().
I Example:
1 list1 = [’apple’, ’banana’, ’cherry’]
2 list2 = list1.copy()
3 print(list2)
4 list3 = list(list1) # Another copy of list 1
5 print(list3)
February 29, 2020 Python Programming 112
List - Join Lists
Arrays
I There are several ways to join, or concatenate, two or more lists in Python.
I One of the easiest ways are by using the + operator.
I Another way to join two lists are by appending all the items from list2 into
list1, one by one:
I You can use the extend() method, which purpose is to add elements from
one list to another list.
I Example:
1 list1 = [’a’, ’b’ , ’c’]
2 list2 = [1, 2, 3]
3 list3 = list1 + list2
4 print(list3)
5
6 list4 = [’a’, ’b’ , ’c’]
7 list5 = [1, 2, 3]
8 for x in list5:
9 list4.append(x)
10 print(list4)
11
12 list6 = [’a’, ’b’ , ’c’]
13 list7 = [1, 2, 3]
14 list6.extend(list7)
15 print(list6)
February 29, 2020 Python Programming 113
List - The list() Constructor
Arrays
I It is also possible to use the list() constructor to make a new list.
I Example:
1 fruits = list((’apple’, ’banana’, ’cherry’)) # note the double round-brackets
2 print(fruits)
February 29, 2020 Python Programming 114
List Methods
Arrays
I append() Adds an element at the end of the list
I clear() Removes all the elements from the list
I copy() Returns a copy of the list
I count() Returns the number of elements with the specified value
I extend() Add the elements of a list (or any iterable), to the end of the
current list
I index() Searches the list for a specified value and returns the position of
where it was found
I insert() Adds an element at the specified position
I pop() Removes the element at the specified position
I remove() Removes the item with the specified value
I reverse() Reverses the order of the list
I sort() Sorts the list
February 29, 2020 Python Programming 115
Multidimensional Lists
Arrays
I List can hold another list.
I A list which holds another list is called a multidimensional list.
I We can create matrices (2D Lists) with multidimensional list.
I Example:
1 2 3
4 5 6
M= 7
8 9
10 11 12
Equivalent Python statement
1 M=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
February 29, 2020 Python Programming 116
Multidimensional Lists - Accessing Elements
Arrays
I Multiple indices are required to access elements
I For example, (x, y)th element of a two dimension array is accessed as
M[x][y].
I Example:
1 2 3 M[0][0] = 1 M[0][1] = 2 M[0][2] = 3
4 5 6 M[1][0] = 4 M[1][1] = 5 M[1][2] = 6
M= 7 8 9 = M[2][0] = 7 M[2][1] = 8 M[2][2] = 9
0 1 2 M[3][0] = 0 M[3][1] = 1 M[3][2] = 2
1 >> M=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
2 >> M[0][0]
3 1
4 >> M[2][1]
5 8
February 29, 2020 Python Programming 117
Multidimensional Lists - Loop through Elements
Arrays
I A for loop can be used access elements in an array.
I Suppose M is an array.
I len(M) gives number of rows in the array.
I len(M[0]) gives number items in the first row of the array.
I In other words, len(M[0]) gives number of columns.
I Example:
1 >> M=[[1,2,3],[4,5,6],[7,8,9],[0,1,2]]
2 >> N=[[2,4,5],[4,2,7],[0,1,2],[8,9,1]]
3 >> P=[[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
4 >> for x in range(len(M)):
5 for y in range(len(M[0])):
6 print(M[x][y])
7 >> for x in range(len(M)):
8 for y in range(len(M[0])):
9 P[x][y]=M[x][y]+N[x][y]
10 >> print(P)
11 [[3, 6, 8], [8, 7, 13], [7, 9, 11], [8, 10, 3]]
February 29, 2020 Python Programming 118
Read 1D array from keyboard
Python Programming Example
1 # Reading 1D array from keyboard
2 N=int(input(’Number of numbers’))
3 array=[]
4 for x in range(N):
5 n=int(input())
6 array.append(n)
7 print(array)
February 29, 2020 Python Programming 119
Read 2D array from keyboard
Python Programming Example
1 # Read number number of rows and columns
2 Rows=int(input(’Number of Rows:’))
3 Colms=int(input(’Number of Colms:’))
4
5 # Create an empty list
6 array=[]
7
8 # Modify the size of array to (Rows, Colms)
9 # Also fill it with zeros
10
11 for i in range(Rows):
12 array.append([0 for x in range(Colms)])
13 print(array)
14
15 # Read elements from keyboard assign to array
16 for x in range(Rows):
17 for y in range(Colms):
18 array[x][y]=int(input())
19 print(array)
February 29, 2020 Python Programming 120
Sum of two matrices
Python Programming Example
1 # Sum of two matrices
2 Rows=int(input(’Number of Rows:’))
3 Colms=int(input(’Number of Colms:’))
4 # Create an empty matrices
5 M=[]
6 N=[]
7 P=[]
8 # Modify the size of matrices to (Rows, Colms)
9 # Also fill it with zeros
10 for i in range(Rows):
11 M.append([0 for x in range(Colms)])
12 N.append([0 for x in range(Colms)])
13 P.append([0 for x in range(Colms)])
14 # Read elements of first array
15 for x in range(Rows):
16 for y in range(Colms):
17 M[x][y]=int(input())
18 # Read elements of second array
19 for x in range(Rows):
20 for y in range(Colms):
21 N[x][y]=int(input())
22 P[x][y]=M[x][y]+N[x][y]
23 # Add two matrices
24 for x in range(Rows):
25 for y in range(Colms):
26 P[x][y]=M[x][y]+N[x][y]
27 print(P)
February 29, 2020 Python Programming 121
The Tuple
The Tuple
February 29, 2020 Python Programming 122
Tuple
Arrays
I A tuple is a collection which is ordered and unchangeable.
I In Python tuples are written with round brackets ().
I Example:
1 >>> fruits = (’apple’, ’banana’, ’cherry’)
2 >>> print(fruits)
I Output:
1 >>>
2 >>> (’apple’, ’banana’, ’cherry’)
February 29, 2020 Python Programming 123
Set
Arrays
fruits = {’apple’, ’banana’, ’cherry’, ’orange’, ’kiwi’}
prices = {10,20,30}
Operator Example Description
Access Items NOT POSSIBLE.
Loop Through a Tuple for x in fruits: Iterate through all items.
Check if Item Exists if ’apple’ in fruits: Apple exists in fruits?
Length len(fruits) Number of elements in fruits.
Add Items NOT POSSIBLE.
Remove Items NOT POSSIBLE.
Join Two Tuples fruits + prices Joint fruits and prices.
creates or convert an array into a
tuple() Constructor fruits=tuple((1,2,3))
tuple.
To create a tuple with only one
item, you have add a comma after
Create Tuple With One Item fruits=(’apple’,)
the item, unless Python will not
recognize the variable as a tuple.
February 29, 2020 Python Programming 124
Tuple - Operations
Arrays
fruits = (’apple’, ’banana’, ’cherry’, ’orange’, ’kiwi’)
prices = (10,20,30)
Operator Example Description
Access Items fruits[2] 3rd item.
Negative Indexing fruits[-1] Last item.
Range of Indexes fruits[2:5] 3rd, 4th and 5th item.
items from index -4 (included) to
Range of Negative Indexes fruits[-4:-1]
index -1. (excluded)
Loop Through a Tuple for x in fruits: Iterate through all items.
Check if Item Exists if ’apple’ in fruits: Apple exists in fruits?
Length len(fruits) Number of elements in fruits.
Add Items NOT POSSIBLE
Remove Items NOT POSSIBLE
Join Two Tuples fruits + prices Joint fruits and prices.
creates or convert an array into a
tuple() Constructor fruits=tuple((1,2,3))
tuple.
To create a tuple with only one
item, you have add a comma after
Create Tuple With One Item fruits=(’apple’,)
the item, unless Python will not
recognize the variable as a tuple.
February 29, 2020 Python Programming 125
Tuple Methods
Arrays
I count() Returns the number of elements with the specified value
I index() Searches the tuple for a specified value and returns the position of
where it was found
February 29, 2020 Python Programming 126
The Set
The Set
February 29, 2020 Python Programming 127
Set
Arrays
I A set is a collection which is unordered and unindexed. In Python sets are
written with curly brackets {}.
I Sets are unordered, so you cannot be sure in which order the items will
appear.
I Sets does not allow duplicate items.
I Example:
1 >>> fruits = {’apple’, ’banana’, ’cherry’}
2 >>> print(fruits)
3 set([’cherry’, ’apple’, ’banana’])
4 >>> fruits = {’apple’,’apple’,’apple’, ’banana’,’banana’ ’cherry’}
5 # duplicate items will be removed
6 >>> print(fruits)
7 set([’cherry’, ’apple’, ’banana’])
February 29, 2020 Python Programming 128
Sets - Operations
Arrays
fruits = {’apple’, ’banana’, ’cherry’}
prices = {10,20,30}
Operator Example Description
Access Items for x in fruits: Iterate through all items.
Check if Item Exists if ’apple’ in fruits: Apple exists in fruits?
Length len(fruits) Number of elements in fruits.
Change Items NOT POSSIBLE
Add a new item ’grape’ to the set
Add Items fruits.add(’grape’)
using add() method
Add two new items to the set using
Add Multiple Items fruits.update(’grape’,’orange’)
update() method
Removes the item ’banana’ from the
Remove Items fruits.remove(’banana’)
set.
Removes the last item ’cherry’ from
Remove Last Item fruits.pop()
the set.
Empties set fruits.clear() Remove all elements from the set.
Delete set del fruits Delete set.
Returns a new set with all items
Join Two Sets fruits.union(prices)
from both sets.
method inserts the items in
Insert Items fruits.update(prices)
’prices’ into ’fruits’.
creates or convert an array
Set() Constructor fruits=set((1,2,3)) into a set. Note the double
round-brackets
February 29, 2020 Python Programming 129
The Dictionary
The Dictionary
February 29, 2020 Python Programming 130
Dictionary
Arrays
I A dictionary is a collection which is unordered, changeable and indexed.
In Python dictionaries are written with curly brackets {}, and they have
keys and values separated by :
I Example:
1 >>> Cars = {’brand’: ’Ford’, ’model’: ’Mustang’, ’year’: 1964}
2 >>> print(Cars)
3 {’brand’: ’Ford’, ’model’: ’Mustang’, ’year’: 1964}
February 29, 2020 Python Programming 131
Dictionary - Accessing Items
Arrays
I You can access the items of a dictionary by referring to its key name, inside
square brackets.
I There is also a method called get() that will give you the same result.
I Example:
1 >>> Cars = {
2 ’brand’: ’Ford’,
3 ’model’: ’Mustang’,
4 ’year’: 1964
5 }
6 >>> Cars[’model’]
7 ’Mustang’
8 >>> Cars.get(’year’)
9 1964
February 29, 2020 Python Programming 132
Dictionary - Change Values
Arrays
I You can change the value of a specific item by referring to its key name.
I Example:
1 >>> Cars = {
2 ’brand’: ’Ford’,
3 ’model’: ’Mustang’,
4 ’year’: 1964
5 }
6 >>> # Change year to 2018
7 >>> Cars[’year’]=2018
8 >>> print(Cars)
9 {’brand’: ’Ford’, ’model’: ’Mustang’, ’year’: 2018}
February 29, 2020 Python Programming 133
Dictionary - Loop through items
Arrays
I You can loop through a dictionary by using a for loop.
I When looping through a dictionary, the return value are the keys of the
dictionary.
I You can also use the values() function to return values of a dictionary.
I Example:
1 >>> # Print all key names
2 >>> for x in Cars:
3 print(x)
4 brand
5 model
6 year
7 >>> # Print all values
8 >>> for x in Cars:
9 print(Cars[x])
10 Ford
11 Mustang
12 2018
13 >>> # Print all values using ’values()’ method
14 >>> for x in Cars.values():
15 print(x)
February 29, 2020 Python Programming 134
Dictionary - Loop through keys and values
Arrays
I Loop through both keys and values, by using the items() function.
I Example:
1 >>> for x, y in Cars.items():
2 >>> print(x, y)
3 (’brand’, ’Ford’)
4 (’model’, ’Mustang’)
5 (’year’, 2018)
February 29, 2020 Python Programming 135
Dictionary - Check if Key Exists
Arrays
I To determine if a specified key is present in a dictionary use the in key-
word.
I Example:
1 # Check if key ’model’ is present in the dictionary:
2 >>> if ’model’ in Cars:
3 >>> print(’model is a key’)
4 ’model is a key’
February 29, 2020 Python Programming 136
Dictionary - Length
Arrays
I To determine how many items (key-value pairs) a dictionary has, use the
len() method.
I Example:
1 >>> print(len(Cars))
2 3
February 29, 2020 Python Programming 137
Dictionary - Adding Items
Arrays
I Adding an item to the dictionary is done by using a new index key and
assigning a value to it:
I Example:
1 >>> Cars = {
2 ’brand’: ’Ford’,
3 ’model’: ’Mustang’,
4 ’year’: 1964
5 }
6 >>> # Add new item with key ’color’
7 >>> Cars[’color’]=’red’
8 >>> print(Cars)
9 {’color’: ’red’, ’brand’: ’Ford’, ’model’: ’Mustang’, ’year’: 2018}
February 29, 2020 Python Programming 138
Dictionary - Removing Items
Arrays
I The pop() method removes the item with the specified key name.
I The del keyword removes the item with the specified key name:
I The del keyword can also delete the dictionary completely
I The clear() method empties the dictionary:
I Example:
1 >>> Cars = {’brand’: ’Ford’,’model’: ’Mustang’, ’year’: 1964 }
2 >>> # Removes item with key ’model’
3 >>> Cars.pop(’model’)
4 ’Mustang’
5 >>> print(Cars)
6 {’brand’: ’Ford’, ’year’: 1964}
7 >>> # Delete item with key ’model’
8 >> del Cars[’year’]
9 >>> print(Cars)
10 {’brand’: ’Ford’}
11 >>> # Empties Dictionary
12 >>> Cars.clear()
13 >>> print(Cars)
14 {}
15 >>> # Delete entire Dictionary - no longer accessible
16 >>> del Cars
February 29, 2020 Python Programming 139
Dictionary - Copy Items
Arrays
I You cannot copy a dictionary simply by typing dict2 = dict1, because:
dict2 will only be a reference to dict1, and changes made in dict1 will
automatically also be made in dict2.
I There are ways to make a copy, one way is to use the built-in Dictionary
method copy().
I Another way is to use dict() method.
I Example:
1 >>> Vehicles = {’brand’: ’Ford’,’model’: ’Mustang’, ’year’: 1964 }
2 >>> # Using copy() method
3 >>> Cars = Vehicles.copy()
4 >>> print(Cars)
5 {’brand’: ’Ford’,’model’: ’Mustang’, ’year’: 1964 }
6 >>> # Using dict() method
7 >>> Cars = dict(Vehicles)
8 >>> print(Cars)
9 {’brand’: ’Ford’,’model’: ’Mustang’, ’year’: 1964 }
February 29, 2020 Python Programming 140
Dictionary - Nested Dictionaries
Arrays
I A dictionary can also contain many dictionaries, this is called nested dic-
tionaries.
I Example:
1 >>> # Create three dictionaries
2 >>> student1 = {’name’ : ’Arun’, ’age’ : 19}
3 >>> student2 = {’name’ : ’Manu’, ’age’ : 18}
4 >>> student3 = {’name’ : ’Vinod’, ’age’ : 20}
5 >>> # Create one dictionary that will contain the other three dictionaries:
6 >>> S4AEClass = {’std1’ : student1, ’std2’ : student2, ’std3’ : student2}
7 >>> print(S4AEClass)
8 {’std1’: {’age’: 19, ’name’: ’Arun’},
9 ’std3’: {’age’: 18, ’name’: ’Manu’},
10 ’std2’: {’age’: 18, ’name’: ’Manu’}
11 }
February 29, 2020 Python Programming 141
Dictionary - The dict() Constructor
Arrays
I It is also possible to use the dict() constructor to make a new dictionary.
I Example:
1 >>> Cars = dict(brand="Ford", model="Mustang", year=1964)
2 >>> # note that keywords are not string literals
3 >>> # note the use of equals rather than colon for the assignment
4 >>> print(Cars)
5 {’model’: ’Mustang’, ’brand’: ’Ford’, ’year’: 1964}
February 29, 2020 Python Programming 142
Dictionary
Arrays
I clear() Removes all the elements from the dictionary
I copy() Returns a copy of the dictionary
I fromkeys() Returns a dictionary with the specified keys and value
I get() Returns the value of the specified key
I items() Returns a list containing a tuple for each key value pair
I keys() Returns a list containing the dictionary’s keys
I pop() Removes the element with the specified key
I popitem() Removes the last inserted key-value pair
I setdefault() Returns the value of the specified key. If the key does not
exist: insert the key, with the specified value
I update() Updates the dictionary with the specified key-value pairs
I values() Returns a list of all the values in the dictionary
February 29, 2020 Python Programming 143
The String
The String
February 29, 2020 Python Programming 144
String
Arrays
I Strings are collection of characters surrounded by either double quotes (")
or single quotes(’).
I ’hello’ is a string literal (A literal is a value that is expressed as itself).
I ’hello’ is the same as "hello".
I Assigning a string to a variable is done with the variable name followed
by an equal sign and the string.
I You can assign a multiline string to a variable by using three quotes.
I Example:
1 >>> str = ’Hello’
2 >>> print(str)
3 Hello
4 >>> # Multiline string
5 >>> str = """ This is a very long
6 multiline string in python
7 enclosed in three quotes."""
8 >>> print(str)
9 This is a very long
10 multiline string in python
11 enclosed in three quotes.
February 29, 2020 Python Programming 145
String - Accessing Elements
Arrays
I Square brackets can be used to access elements of the string.
I Example:
1 >>> str = ’PYTHON’
2 >>> print(str[2])
3 T
February 29, 2020 Python Programming 146
String - Slicing
Arrays
I You can return a range of characters by using the slice syntax.
I Specify the start index and the end index, separated by a colon, to return
a part of the string
I Use negative indexes to start the slice from the end of the string.
I Example:
1 >>> str=’PYTHON’
2 >>> print(str[2:5])
3 ’THO’
4 >>> # Access first element
5 >>> print(str[0])
6 ’N’
7 >>> # Access last element
8 >>> print(str[-1])
9 ’N’
10 >>> # Get the characters from position 5 to position 1, starting the count from
the end of the string.
11 >>> print(str[-5:-2])
12 >>> ’YTH’
February 29, 2020 Python Programming 147
String - Length
Arrays
I To get the length of a string, use the len() function.
I Example:
1
2 >>> str = ’PYTHON’
3 >>> print(len(str))
4 6
February 29, 2020 Python Programming 148
String - Methods
Arrays
I The strip() method removes any whitespace from the beginning or the
end.
I The lower() method returns the string in lower case.
I The upper() method returns the string in upper case.
I Example:
1 >>> str = ’ PYTHON Is Interesting ’ #See whites space at the beginning and end
2 >>> print(str.strip()) # remove white spaces
3 PYTHON Is Interesting
4 >>> print(str.upper()) # Convert to uppercase
5 PYTHON IS INTERESTING
6 >>> print(str.lower()) # Convert to lowercase
7 python is interesting
February 29, 2020 Python Programming 149
String - Methods
Arrays
I The replace() method replaces a string with another. string.
I The split() method splits the string into substrings if it finds instances of
the separator.
I Example:
1 >>> str = ’Python,Basic,Cobol’
2 >>> newstr=str.replace(’Python’,’Java’) # Replace ’Python’ by ’Java’
3 >>> print(newstr)
4 Java, Basic, Cobol
5 >>> # Split string into a list of substrings
6 >>> # Separator is ’,’ (comma)
7 >>> print(str.split(’,’))
8 [’Python’, ’Basic’, ’Cobol’]
9 >>> # Separator is ’;’ (Semi-colon)
10 >>> str = ’Apple; Banana; Grapes’
11 >>> print(str.split(’;’))
12 [’Apple’, ’Banana’, ’Grapes’]
February 29, 2020 Python Programming 150
String - Check String
Arrays
I To check if a certain phrase or character is present in a string, we can use
the keywords in or not in.
I Example:
1
2 >>> msg = ’the quick fox jumps over the lazy dog’
3 >>> x = ’fox’ in msg
4 >>> print(x)
5 True
6 >>> y= ’rabbit’ not in msg
7 >>> print(x)
8 True
February 29, 2020 Python Programming 151
String - Concatenation
Arrays
I To concatenate, or combine, two strings you can use the + operator.
I To add a space between them, add a ’ ’ or " "
I Example:
1 >>> str1 = ’Python’
2 >>> str2 = ’is interesting’
3 >>> msg = str1 + str2
4 >>> print(msg)
5 Pythonis interesting
6 >>> msg = str1 + ’ ’ + str2
7 Python is interesting
February 29, 2020 Python Programming 152
String - Concatenation
Arrays
I The str() can be used to convert an object into string.
I Example:
1 >>> a=2
2 >>> b=3
3 >>> c=a+b
4 >>> info = ’The sum of ’ + str(a) + ’ and ’ + str(b) + ’ is ’ + str(c)
5 >>> print(info)
6 The sum of 2 and 3 is 5
February 29, 2020 Python Programming 153
String - Repeating
Arrays
I he repetition operator is denoted by a ’*’ symbol and is useful for repeating
strings to a certain length
I Example:
1
2 >>> str = ’Python program-’
3 >>> # Repeat string five times
4 >>> msg= str*5
5 >>> print(msg)
6 Python program-Python program-Python program-Python program-Python program-
February 29, 2020 Python Programming 154
String - Formatting
Arrays
I We can combine strings and numbers by using the format() method.
I The format() method takes the passed arguments, formats them, and
places them in the string where the placeholders {} are there.
I You can use index numbers like {0},{1},{2} to be sure the arguments are
placed in the correct placeholders.
I Example:
1
2 >>> age = 19
3 >>> grade = ’O+’
4 >>> name = ’Arun’
5 >>> info = ’I am {} years old’
6 >>> print(info.format(age))
7 I am 19 years old
8 >>> info = ’{} is {} years old. His grade is {}’
9 >>> print(info.format(name,age,grade))
10 Arun is 19 years old. His grade is O+
11 >>> # Positions of items are specified
12 >>> info = ’{2} is {1} years old. His grade is {0}’
13 >>> # Please note the order of items: 0th->grade, 1st->age, 2nd->name
14 >>> print(info.format(grade,name,name))
15 Arun is 19 years old. His grade is O+
February 29, 2020 Python Programming 155
String - Escape Character
Arrays
I To insert characters that are illegal in a string, use an escape character.
I An escape character is a backslash \ followed by the character you want
to insert.
I An example of an illegal character is a single quote (’) inside a string that
is surrounded by single quotes (’).
I Example:
1
2 >>> ’The class ’S4EC’ contain geniuses’
3 File "<stdin>", line 1
4 ’The class ’S4EC’ contain geniuses’
5 ^
6 SyntaxError: invalid syntax
7 >>> # The correct way
8 >>> ’The class \’S4EC\’ contain geniuses’
9 "The class ’S4EC’ contain geniuses"
February 29, 2020 Python Programming 156
String - Escape Character
Arrays
I The string escape characters are listed below.
\’ Single Quote
\" Double Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
February 29, 2020 Python Programming 157
String - Escape Character
Arrays
I Examples:
1 >>> # \n is the new line character
2 >>> print(’This is first line.\nThis is new line.’)
3 This is first line.
4 This is new line.
5 >>> # \t is the tab character
6 >>> print(’1\t2\t3\t’)
7 1 2 3
February 29, 2020 Python Programming 158
String - Functions
Arrays
I capitalize(): Converts the first character to upper case
I casefold(): Converts string into lower case
I center(): Returns a centered string
I count(): Returns the number of times a specified value occurs in a string
I encode(): Returns an encoded version of the string
I endswith(): Returns true if the string ends with the specified value
I expandtabs(): Sets the tab size of the string
I find(): Searches the string for a specified value and returns the position of
where it was found
I format(): Formats specified values in a string
I format_map(): Formats specified values in a string
I index(): Searches the string for a specified value and returns the position
of where it was found
February 29, 2020 Python Programming 159
String - Functions
Arrays
I isalnum(): Returns True if all characters in the string are alphanumeric
I isalpha(): Returns True if all characters in the string are in the alphabet
I isdecimal(): Returns True if all characters in the string are decimals
I isdigit(): Returns True if all characters in the string are digits
I isidentifier(): Returns True if the string is an identifier
I islower(): Returns True if all characters in the string are lower case
I isnumeric(): Returns True if all characters in the string are numeric
I isprintable(): Returns True if all characters in the string are printable
I isspace(): Returns True if all characters in the string are whitespaces
I istitle(): Returns True if the string follows the rules of a title
I isupper(): Returns True if all characters in the string are upper case
I join(): Joins the elements of an iterable to the end of the string
I ljust(): Returns a left justified version of the string
February 29, 2020 Python Programming 160
String - Functions
Arrays
I lower(): Converts a string into lower case
I lstrip(): Returns a left trim version of the string
I maketrans(): Returns a translation table to be used in translations
I partition(): Returns a tuple where the string is parted into three parts
I replace(): Returns a string where a specified value is replaced with a spec-
ified value
I rfind(): Searches the string for a specified value and returns the last posi-
tion of where it was found
I rindex(): Searches the string for a specified value and returns the last
position of where it was found
I rjust(): Returns a right justified version of the string
I rpartition(): Returns a tuple where the string is parted into three parts
I rsplit(): Splits the string at the specified separator, and returns a list
I rstrip(): Returns a right trim version of the string
February 29, 2020 Python Programming 161
String - Functions
Arrays
I split(): Splits the string at the specified separator, and returns a list
I splitlines(): Splits the string at line breaks and returns a list
I startswith(): Returns true if the string starts with the specified value
I strip(): Returns a trimmed version of the string
I swapcase(): Swaps cases, lower case becomes upper case and vice versa
I title(): Converts the first character of each word to upper case
I translate(): Returns a translated string
I upper(): Converts a string into upper case
I zfill(): Fills the string with a specified number of 0 values at the beginning
February 29, 2020 Python Programming 162