Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Introduction To Programming With Python

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 170

Introduction to Programming

with Python
Deependra Rastogi
Assistant Professor, CCSIT
TMU

1
Languages
 Some influential ones:
 FORTRAN
 science / engineering

 COBOL
 business data

 LISP
 logic and AI

 BASIC
 a simple language

2
Programming basics
 code or source code: The sequence of instructions in a program.

 syntax: The set of legal structures and commands that can be


used in a particular programming language.

 output: The messages printed to the user by a program.

 console: The text box onto which output is printed.


 Some source code editors pop up the console as an external window,
and others contain their own console window.

3
Compiling and interpreting
 Many languages require you to compile (translate) your program
into a form that the machine understands.
compile execute
source code byte code output
Hello.java Hello.class

 Python is instead directly interpreted into machine instructions.

interpret
source code output
Hello.py

4
Python Program Structure

5
Python Identifier
 A Python identifier is a name used to identify a variable, function,
class, module or other object. An identifier starts with a letter A to
Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
 Python does not allow punctuation characters such as @, $, and %
within identifiers. Python is a case sensitive programming
language. Thus, Manpower and manpower are two different
identifiers in Python.
 Here are naming conventions for Python identifiers −
 Class names start with an uppercase letter. All other identifiers start
with a lowercase letter.
 Starting an identifier with a single leading underscore indicates that the
identifier is private.
 Starting an identifier with two leading underscores indicates a strongly
private identifier.
 If the identifier also ends with two trailing underscores, the identifier is
a language-defined special name.
6
Reserved Word

and exec not


assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield

7
Lines and Indentation
 Python provides no braces to indicate blocks of code for class and
function definitions or flow control. Blocks of code are denoted by
line indentation, which is rigidly enforced.
 The number of spaces in the indentation is variable, but all
statements within the block must be indented the same amount.
For example −

if True:
print "True"
else:
print "False"

8
Lines and Indentation
 However, the following block generates an error −

if True:
print "Answer"
print "True"
else:
print "Answer"
print "False“

Thus, in Python all the continuous lines indented with same number
of spaces would form a block.

9
Lines and Indentation
 However, the following block generates an error −

if True:
print "Answer"
print "True"
else:
print "Answer"
print "False“

Thus, in Python all the continuous lines indented with same number
of spaces would form a block.

10
Multi Line Statement
Statements in Python typically end with a new line. Python does,
however, allow the use of the line continuation character (\) to
denote that the line should continue. For example −

total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to
use the line continuation character. For example −

days = ['Monday', 'Tuesday', 'Wednesday',


'Thursday', 'Friday']

11
Quotation in Python
 Python accepts single ('), double (") and triple (''' or """) quotes to
denote string literals, as long as the same type of quote starts and
ends the string.
 The triple quotes are used to span the string across multiple lines.
For example, all the following are legal −

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""

12
Comment in Python
A hash sign (#) that is not inside a string literal begins a comment.
All characters after the # and up to the end of the physical line are
part of the comment and the Python interpreter ignores them.

#!/usr/bin/python

# First comment

print "Hello, Python!" # second comment

13
print() in Python
In Python a function is a group of statements that are put together to
perform a specific task. The task of print function is to display the
contents on the screen. The syntax of print function is

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

 print() Parameters
 objects - object to the printed. * indicates that there may be more
than one object
 sep - objects are separated by sep. Default value: ' '
 end - end is printed at last
 file - must be an object with write(string) method. If omitted
it, sys.stdout will be used which prints objects on the screen.
 flush - If True, the stream is forcibly flushed. Default value: False

14
print() in Python
The argument of the print function can be a value of any type int,
str, float etc. it also be a value stored in a variable.

Example
print("Python is fun.")
a=5

# Two objects are passed


print("a =", a)
Output
b=a
Python is fun.
# Three objects are passed a=5
print('a =', a, '= b') a=5=b

15
Variable
In most of the programming languages a variable is a named location
used to store data in the memory. Each variable must have a unique
name called identifier. It is helpful to think of variables as container
that hold data which can be changed later throughout programming.

Note: In Python we don't assign values to the variables, whereas


Python gives the reference of the object (value) to the variable.

16
Variable
 Declaring Variables in Python
In Python, variables do not need declaration to reserve memory
space. The "variable declaration" or "variable initialization" happens
automatically when we assign a value to a variable.

Assigning value to a Variable in Python

website = "Apple.com“
print(website)

Note : Python is a type inferred language, it can automatically infer


(know) Apple.com is a String and declare website as a String.

17
Variable
website = "Apple.com“
# assigning a new variable to website

website = "Programiz.com“
print(website)

Assigning multiple values to multiple variables


a, b, c = 5, 3.2, "Hello“
print (a)
print (b)
print (c)

18
Variable
If we want to assign the same value to multiple variables at once, we
can do this as

x = y = z = "same“
print (x)
print (y)
print (z)

19
Variable
Rules and Naming convention for variables and constants
Create a name that makes sense. Suppose, vowel makes more

sense than v.
Use camelCase notation to declare a variable. It starts with

lowercase letter. For example:


myName
myAge
myAddress

Use capital letters where possible to declare a constant. For


example:
PI
G
MASS
TEMP

20
Variable
 Never use special symbols like !, @, #, $, %, etc.
 Don't start name with a digit.
 Constants are put into Python modules and meant not be changed.
 Constant and variable names should have combination of letters in
lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an
underscore (_). For example:
snake_case
MACRO_CASE
camelCase C
apWords

21
Literals
Literal is a raw data given in a variable or constant. In Python, there
are various types of literals they are as follows:

 Numeric Literals
 String Literals
 Boolean Literals
 Special Literals
 Literal Collection

22
Literals
Numeric Literals
Numeric Literals are immutable (unchangeable). Numeric literals can

belong to 3 different numerical types Integer, Float and Complex.


a = 0b1010 #Binary Literals
b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal

#Float Literal
float_1 = 10.5
float_2 = 1.5e2

#Complex Literal
x = 3.14j
print(a, b, c, d)
print(float_1, float_2)
print(x, x.imag, x.real)

23
Literals
String literals
A string literal is a sequence of characters surrounded by quotes. We
can use both single, double or triple quotes for a string. And, a
character literal is a single character surrounded by single or double
quotes.

24
Literals
Boolean literals
A Boolean literal can have any of the two values: True or False.

25
Literals
Literal Collections
There are four different literal collections List literals, Tuple literals,
Dict literals, and Set literals.

26
Literals
Special literals
Python contains one special literal i.e. None. We use it to specify to
that field that is not created.

27
input() in python
The input() method reads a line from input, converts into a string
and returns it.

28
input() in python
Return value from input()
The input() method reads a line from input (usually user), converts
the line into a string by removing the trailing newline, and returns it.

29
input() in python

30
Python Type Conversion
The process of converting the value of one data type (integer, string,
float, etc.) to another data type is called type conversion. Python has
two types of type conversion.

Implicit Type Conversion


Explicit Type Conversion

Implicit Type Conversion:


In Implicit type conversion, Python automatically converts one data
type to another data type. This process doesn't need any user
involvement.
Let's see an example where Python promotes conversion of lower
datatype (integer) to higher data type (float) to avoid data loss.

31
Python Type Conversion

32
Python Type Conversion

33
Python Type Conversion

34
Python Type Conversion
 Explicit Type Conversion:
In Explicit Type Conversion, users convert the data type of an object
to required data type. We use the predefined functions
like int(), float(), str(), etc to perform explicit type conversion.

This type conversion is also called typecasting because the user casts
(change) the data type of the objects.

Syntax :
(required_datatype)(expression)

35
Python Type Conversion

36
Python Type Conversion

37
Python Type Conversion
 Type Conversion is the conversion of object from one data type to
another data type.
 Implicit Type Conversion is automatically performed by the Python
interpreter.
 Python avoids the loss of data in Implicit Type Conversion.
 Explicit Type Conversion is also called Type Casting, the data types
of object are converted using predefined function by user.
 In Type Casting loss of data may occur as we enforce the object to
specific data type.

38
Example Programs
#Simple Interest

P=float(input("Enter Priciple Amount:"))


R=float(input("Enter Rate:"))
T=float(input("Enter Time:"))

SI=(P * R * T)/100

print("Simple Interest is", SI)

39
Example Programs
#Compound Interest

P=float(input("Enter Priciple Amount:"))


R=float(input("Enter Rate:"))
T=float(input("Enter Time:"))

CI = P * (pow((1 + R / 100), T))


print("Compound interest is", CI)

40
Example Programs
#Compound Interest

P=float(input("Enter Priciple Amount:"))


R=float(input("Enter Rate:"))
T=float(input("Enter Time:"))

CI = P * (pow((1 + R / 100), T))


print("Compound interest is", CI)

41
Example Programs
#Program to find area of a circle

42
Output formatting
Sometimes we would like to format our output to make it look
attractive. This can be done by using the str.format() method. This
method is visible to any string object.

43
Output formatting

44
Output formatting

45
Operator

46
Operator

47
Operator

48
Operator

49
Operator

50
Operator

51
Operator

52
Operator

53
Operator

54
Operator
# Python Program to calculate the square root

num = float(input('Enter a number: '))


num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)) 

55
Operator
# Python Program to find the area of triangle

a = float(input('Enter first side: '))


b = float(input('Enter second side: '))
c = float(input('Enter third side: '))

# calculate the semi-perimeter


s = (a + b + c) / 2

# calculate the area


area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

56
Operator
# Solve the quadratic equation ax**2 + bx + c = 0

# import complex math module


import cmath

# To take coefficient input from the users


a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))

# calculate the discriminant


d = (b**2) - (4*a*c)

# find two solutions


sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print('The solution are {0} and {1}'.format(sol1,sol2))

57
Operator
# Solve the quadratic equation ax**2 + bx + c = 0

# import complex math module


import cmath

# To take coefficient input from the users


a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))

# calculate the discriminant


d = (b**2) - (4*a*c)

# find two solutions


sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print('The solution are {0} and {1}'.format(sol1,sol2))

58
Repetition (loops)
and Selection (if/else)

59
The for loop
 for loop: Repeats a set of statements over a group of values.
 Syntax:
for variableName in groupOfValues:
statements
 We indent the statements to be repeated with tabs or spaces.
 variableName gives a name to each value, so you can refer to it in the statements.
 groupOfValues can be a range of integers, specified with the range function.

 Example:
for x in range(1, 6):
print x, "squared is", x * x

Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25

60
The for loop
 for loop: Repeats a set of statements over a group of values.
 Syntax:
for variableName in groupOfValues:
statements
 We indent the statements to be repeated with tabs or spaces.
 variableName gives a name to each value, so you can refer to it in the statements.
 groupOfValues can be a range of integers, specified with the range function.

 Example:
for x in range(1, 6):
print x, "squared is", x * x

Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25

61
The for loop
# Program to find the sum of all numbers stored in a list

# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# variable to store the sum


sum = 0

# iterate over the list


for val in numbers:
sum = sum+val

# Output: The sum is 48


print("The sum is", sum)

62
The for loop
for loop with else
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.
break statement can be used to stop a for loop. In such case, the else part is ignored.
Hence, a for loop's else part runs if no break occurs.

digits = [0, 1, 5]

for i in digits:
print(i)
else:
print("No items left.")

63
range
 The range function specifies a range of integers:
 range(start, stop) - the integers between start (inclusive)
and stop (exclusive)
 It can also accept a third value specifying the change between values.
 range(start, stop, step) - the integers between start (inclusive)
and stop (exclusive) by step
 Example:
for x in range(5, 0, -1):
print x
print "Blastoff!"
Output:
5
4
3
2
1
Blastoff!

64
range
# Program to iterate through a list using indexing

genre = ['pop', 'rock', 'jazz']

# iterate over the list using index


for i in range(len(genre)):
print("I like", genre[i])

65
Cumulative loops
 Some loops incrementally compute a value that is initialized outside
the loop. This is sometimes called a cumulative sum.
sum = 0
for i in range(1, 11):
sum = sum + (i * i)
print "sum of first 10 squares is", sum

Output:
sum of first 10 squares is 385

66
if
 if statement: Executes a group of statements only if a certain
condition is true. Otherwise, the statements are skipped.
 Syntax:
if condition:
statements

 Example:
gpa = 3.4
if gpa > 2.0:
print "Your application is accepted."

67
if/else
 if/else statement: Executes one block of statements if a certain
condition is True, and a second block of statements if it is False.
 Syntax:
if condition:
statements
else:
statements

 Example:
gpa = 1.4
if gpa > 2.0:
print "Welcome to Mars University!"
else:
print "Your application is denied."

 Multiple conditions can be chained with elif ("else if"):


if condition:
statements
elif condition:
statements
else:
statements
68
while
 while loop: Executes a group of statements as long as a condition is True.
 good for indefinite loops (repeat an unknown number of times)

 Syntax:
while condition:
statements
 Example:
number = 1
while number < 200:
print number,
number = number * 2

 Output:
1 2 4 8 16 32 64 128

69
while
# numbers upto
# sum = 1+2+3+...+n

# To take input from the user,


n = int(input("Enter n: "))

# initialize sum and counter


sum = 0
i=1

while i <= n:
sum = sum + i
i = i+1 # update counter

# print the sum


print("The sum is", sum)

70
while
 while loop with else
 Same as that of for loop, we can have an optional else block with while loop as well.
 The else part is executed if the condition in the while loop evaluates to False.
 The while loop can be terminated with a break statement. In such case, the else part
is ignored. Hence, a while loop's else part runs if no break occurs and the condition
is false.

71
Examples
# Python program to check if the input number is prime or not

# take input from the user


num = int(input("Enter a number: "))

# prime numbers are greater than 1


if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")

# if input number is less than


# or equal to 1, it is not prime
else:
print(num,"is not a prime number")

72
Examples
# Python program to display all the prime numbers within an interval

# uncomment the following lines to take input from the user


lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))

print("Prime numbers between",lower,"and",upper,"are:")

for num in range(lower,upper + 1):


# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)

73
Examples
# Python program to find the factorial of a number provided by the user.

num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

74
Examples
# Program to display the Fibonacci sequence up to n-th term where n is provided by the
user

nterms = int(input("How many terms? "))

# first two terms


n1 = 0
n2 = 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count < nterms:
print(n1,end=' , ')
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
75
Examples
#Check Armstrong number of n digits
num = int(input("Enter a number: "))

# Changed num variable to string,


# and calculated the length (number of digits)
order = len(str(num))

# initialize sum
sum = 0

# find the sum of the cube of each digit


temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10

# display the result


if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

76
Examples
# Python program to find the largest number among the three input numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number between",num1,",",num2,"and",num3,"is",largest)

77
Examples
# Program to check Armstrong numbers in certain interval

lower = int(input("Enter lower range: "))


upper = int(input("Enter upper range: "))

for num in range(lower, upper + 1):

# order of number
order = len(str(num))

# initialize sum
sum = 0

# find the sum of the cube of each digit


temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10

if num == sum:
print(num)

78
Examples
# Program to check Armstrong numbers in certain interval

lower = int(input("Enter lower range: "))


upper = int(input("Enter upper range: "))

for num in range(lower, upper + 1):

# order of number
order = len(str(num))

# initialize sum
sum = 0

# find the sum of the cube of each digit


temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10

if num == sum:
print(num)

79
Examples
#Number is Even or Odd

num = int(input("Enter a number: "))


if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))

80
Examples
# Python program to check if the input year is a leap year or not

year = int(input("Enter a year: "))

if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))

81
List, Tuple, String and Dictionary

82
How to create list?
 In Python programming, a list is created by placing all the items (elements) inside a
square bracket [ ], separated by commas.
 It can have any number of items and they may be of different types (integer, float,
string etc.).

# empty list

my_list = []

# list of integers

my_list = [1, 2, 3]

# list with mixed datatypes

my_list = [1, "Hello", 3.4]

83
How to create list?
Also, a list can even have another list as an item. This is called
nested list.

# nested list

my_list = ["mouse", [8, 4, 6], ['a']]

84
How to access elements from a list?
 List Index
 We can use the index operator [] to access an item in a list. Index
starts from 0. So, a list having 5 elements will have index from 0 to
4.
 Trying to access an element other that this will raise an IndexError.
The index must be an integer. We can't use float or other types,
this will result into TypeError.
 Nested list are accessed using nested indexing.

85
How to access elements from a list?

86
How to access elements from a list?
Negative indexing
Python allows negative indexing for its sequences. The index of -1
refers to the last item, -2 to the second last item and so on.

87
How to slice lists in Python?
We can access a range of items in a list by using the slicing operator
(colon).

88
How to change or add elements to a list?
 List are mutable, meaning,
their elements can be
changed
unlike string or tuple.
 We can use assignment
operator (=) to change an
item or a range of items.

89
How to change or add elements to a list?
 We can add one item to a list
using append() method or
add several items
using extend()method.

90
list.append(item)

How to change or add elements to a list?


The append() method adds a The extend() extends the list
single item to the existing list. by adding all items of a list
It doesn't return a new list; (passed as an argument) to the
rather it modifies the original end.
list. The syntax of extend() method
The syntax of append() method is:
is: list1.extend(list2)
list.append(item) Here, the elements of list2 are
added to the end of list1.
append() Parameters
The append() method takes a extend() Parameters
single item and adds it to the As mentioned, the extend()

end of the list. method takes a single


The item can be numbers, argument (a list) and adds it to
strings, another list, dictionary the end.
etc.
91
list.append(item)

How to change or add elements to a list?

92
list.append(item)

How to change or add elements to a list?

93
list.append(item)

How to change or add elements to a list?

94
How to change or add elements to a list?
 We can also use + operator
to combine two lists. This is
also called concatenation.
 The * operator repeats a list
for the given number of
times.

95
How to change or add elements to a list?
 Furthermore, we can insert
one item at a desired location
by using the
method insert() or insert
multiple items by squeezing it
into an empty slice of a list.

96
How to change or add elements to a list?
 Furthermore, we can insert one item at a desired location by using
the method insert() or insert multiple items by squeezing it into
an empty slice of a list.

insert() Parameters
The insert() function takes two parameters:
index - position where an element needs to be inserted
element - this is the element to be inserted in the list

97
How to change or add elements to a list?
Return Value from insert()
The insert() method only inserts the element to the list. It doesn't
return anything; returns None.

98
How to change or add elements to a list?
Inserting a Tuple (as an Element) to the List

99
How to delete or remove elements from a
list?
 We can delete one or
more items from a list
using the keyword del. It
can even delete the list
entirely.

100
How to delete or remove elements from a
list?
We can use remove() method to remove the given item
or pop() method to remove an item at the given index.

The pop() method removes and returns the last item if index is not


provided. This helps us implement lists as stacks (first in, last out
data structure).

We can also use the clear() method to empty a list.

101
How to delete or remove elements from a
list?

102
How to delete or remove elements from a
list?
remove() Method on a List having Duplicate Elements

103
How to delete or remove elements from a
list?
 pop() parameter
 The pop() method takes a single argument (index) and removes
the item present at that index.
 If the index passed to the pop() method is not in range, it
throws IndexError: pop index out of range exception.
 The parameter passed to the pop() method is optional. If no
parameter is passed, the default index -1 is passed as an
argument which returns the last item.

104
How to delete or remove elements from a
list?
Print Element Present at the Given Index from the List

105
How to delete or remove elements from a
list?
pop() without an index, and for negative indices

106
How to delete or remove elements from a
list?
pop() without an index, and for negative indices

107
Python List Method

108
Python List Method
Python List count()
The count() method returns the number of occurrences of an
element in a list.

In simple terms, count() method counts how many times an


element has occurred in a list and returns it.

The syntax of count() method is:


list.count(element)

 count() Parameters
The count() method takes a single argument:
element - element whose count is to be found.

109
Python List Method
Count the occurrence of an element in the list

110
Python List Method
List reverse()
The reverse() method reverses the elements of a given list.

The syntax of reverse() method is:


list.reverse()

111
Python List Method
 Reverse a List Using Slicing Operator

112
Python List Method
 Accessing Individual Elements in Reversed Order

113
Python List Method
List sort()
The sort() method sorts the elements of a given list in a specific order -

Ascending or Descending.
The syntax of sort() method is:

list.sort(key=..., reverse=...)
Alternatively, you can also use Python's in-built function sorted() for the same

purpose.
sorted(list, key=..., reverse=...)

Note: Simplest difference between sort() and sorted() is: sort() doesn't return
any value while, sorted() returns an iterable list.
sort() Parameters
By default, sort() doesn't require any extra parameters. However, it has two
optional parameters:
reverse - If true, the sorted list is reversed (or sorted in Descending order)
key - function that serves as a key for the sort comparison

114
Python List Method
Sort a given list

115
Python List Method
How to sort in Descending order?

116
Python List Method
 How to sort using your own function with key parameter?
 If you want your own implementation for sorting, sort() also accepts
a key function as an optional parameter.
 Based on the results of the key function, you can sort the given list.
list.sort(key=len)
 Alternatively for sorted
sorted(list, key=len)

 Here, len is the Python's in-built function to count the length of an


element.
 The list is sorted based on the length of its each element, from
lowest count to highest.

117
Python List Method
Sort the list using key

118
Python List Method

119
Python List Method
 Matrix Addition using Nested List Comprehension

120
Python List Method

121
Python List Example

122
Python List Example

123
Python List Example

124
Python Tuple
 What is tuple?
In Python programming, a tuple is similar to a list. The difference between the two is
that we cannot change the elements of a tuple once it is assigned whereas in a list,
elements can be changed.

 Advantages of Tuple over List


Since, tuples are quite similiar to lists, both of them are used in similar situations as well.
However, there are certain advantages of implementing a tuple over a list. Below listed are some
of the main advantages:
 We generally use tuple for heterogeneous (different) datatypes and list for homogeneous (similar)
datatypes.
 Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight
performance boost.
 Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not
possible.
 If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-
protected.

125
Creating a Tuple
 A tuple is created by placing
all the items (elements) inside
a parentheses (), separated by
comma. The parentheses are
optional but is a good practice
to write it.
 A tuple can have any number
of items and they may be of
different types (integer, float,
list, string etc.).

126
Creating a Tuple
 Creating a tuple with one
element is a bit tricky.
 Having one element within
parentheses is not enough.
We will need a trailing
comma to indicate that it is
in fact a tuple.

127
Accessing Elements in a Tuple
Indexing
We can use the index operator []

to access an item in a tuple where


the index starts from 0.
So, a tuple having 6 elements will

have index from 0 to 5. Trying to


access an element other that (6,
7,...) will raise an IndexError.
The index must be an integer, so

we cannot use float or other types.


This will result into TypeError.

128
Changing a Tuple
 Unlike lists, tuples are
immutable.
 This means that elements
of a tuple cannot be
changed once it has been
assigned. But, if the
element is itself a mutable
datatype like list, its
nested items can be
changed.
 We can also assign a tuple
to different values
(reassignment).

129
Deleting a Tuple
 we cannot change the elements in a tuple. That also means we
cannot delete or remove items from a tuple.
 But deleting a tuple entirely is possible using the keyword del.

130
Built-in Functions with Tuple

131
Built-in Functions with Tuple

132
Built-in Functions with Tuple
Python any()

133
Built-in Functions with Tuple
Python len()

134
Python Dictionary
What is dictionary in Python?
Python dictionary is an unordered collection of items. While other

compound data types have only value as an element, a dictionary


has a key: value pair.
Dictionaries are optimized to retrieve values when the key is

known.

How to create a dictionary?


Creating a dictionary is as simple as placing items inside curly

braces {} separated by comma.


An item has a key and the corresponding value expressed as a

pair, key: value.


While values can be of any data type and can repeat, keys must be

of immutable type (string, number or tuple with immutable


elements) and must be unique.

135
Python Dictionary

136
How to access elements from a dictionary?
 While indexing is used with other container types to access
values, dictionary uses keys. Key can be used either inside square
brackets or with the get() method.
 The difference while using get() is that it returns None instead
of KeyError, if the key is not found.

137
How to change or add elements in a
dictionary?
 Dictionary are mutable. We can add new items or change the
value of existing items using assignment operator.
 If the key is already present, value gets updated, else a new key:
value pair is added to the dictionary.

138
How to delete or remove
elements from a dictionary?
 We can remove a particular
item in a dictionary by
using the method pop().
This method removes as
item with the provided key
and returns the value.
 The method, popitem() can
be used to remove and
return an arbitrary item
(key, value) form the
dictionary. All the items can
be removed at once using
the clear() method.
 We can also use
the del keyword to remove
individual items or the
entire dictionary itself.
139
How to delete or remove elements from a
dictionary?

140
Python Dictionary Comprehension
 Dictionary comprehension is an elegant and concise way to create
new dictionary from an iterable in Python.
 Dictionary comprehension consists of an expression pair (key:
value) followed by forstatement inside curly braces {}.
 Here is an example to make a dictionary with each item being a
pair of a number and its square.

141
Python Dictionary Comprehension

142
Python Dictionary Comprehension
Here are some examples to make dictionary with only odd items.

143
Python Nested Dictionary

144
Python Nested Dictionary
Create a Nested Dictionary

145
Python Nested Dictionary
 Access elements of a Nested Dictionary

146
Python Nested Dictionary
 Add element to a Nested Dictionary

147
Python Nested Dictionary
 Add another dictionary to the nested dictionary

148
Python Nested Dictionary
 Delete elements from a Nested Dictionary

149
Python Nested Dictionary
 How to delete dictionary from a nested dictionary?

150
Python Nested Dictionary
 How to iterate through a Nested dictionary?

151
Python String
 A string is a sequence of characters.
 A character is simply a symbol. For example, the English
language has 26 characters.
 Computers do not deal with characters, they deal with numbers
(binary). Even though you may see characters on your screen,
internally it is stored and manipulated as a combination of 0's and
1's.
 This conversion of character to a number is called encoding, and
the reverse process is decoding. ASCII and Unicode are some of
the popular encoding used.
 In Python, string is a sequence of Unicode character. Unicode was
introduced to include every character in all languages and bring
uniformity in encoding. You can learn more about Unicode from
here.

152
How to create a string in Python?
Strings can be created by enclosing characters inside a single quote
or double quotes. Even triple quotes can be used in Python but
generally used to represent multiline strings and docstrings.

153
How to access characters in a string?
 We can access individual characters using indexing and a range
of characters using slicing. Index starts from 0. Trying to access a
character out of index range will raise an IndexError. The index
must be an integer. We can't use float or other types, this will
result into TypeError.
 Python allows negative indexing for its sequences.
 The index of -1 refers to the last item, -2 to the second last item
and so on. We can access a range of items in a string by using
the slicing operator (colon).

154
How to access characters in a string?

155
Python String Operations
 Concatenation of Two or More Strings
 Joining of two or more strings into a single one is called
concatenation.
 The + operator does this in Python. Simply writing two string
literals together also concatenates them.
 The * operator can be used to repeat the string for a given
number of times.

156
Python String Operations
 Built-in functions to Work with Python
 Various built-in functions that work with sequence, works with
string as well.
 Some of the commonly used ones are enumerate() and len().
The enumerate() function returns an enumerate object. It
contains the index and value of all the items in the string as
pairs. This can be useful for iteration.
 Similarly, len() returns the length (number of characters) of the
string.

157
Python String Formatting
 Escape Sequence
 If we want to print a text like -He said, "What's there?"- we can
neither use single quote or double quotes. This will result
into SyntaxError as the text itself contains both single and double
quotes.
 One way to get around this problem is to use triple quotes.
Alternatively, we can use escape sequences.
 An escape sequence starts with a backslash and is interpreted
differently. If we use single quote to represent a string, all the
single quotes inside the string must be escaped. Similar is the
case with double quotes. Here is how it can be done to represent
the above text.

158
Python String Formatting

159
Python String Formatting
 Raw String to ignore escape sequence
 Sometimes we may wish to ignore the escape sequences inside a
string. To do this we can place r or R in front of the string. This
will imply that it is a raw string and any escape sequence inside it
will be ignored.

 The format() Method for Formatting Strings


 The format() method that is available with the string object is
very versatile and powerful in formatting strings. Format strings
contains curly braces {} as placeholders or replacement fields
which gets replaced.
 We can use positional arguments or keyword arguments to
specify the order.

160
Python String Formatting

161
Common Python String Methods

162
String Example

163
String Example

164
String Example

165
String Methods

166
String Methods

167
String Methods

168
String Methods

169
String Methods

170

You might also like