Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

Programing

Part-II
Prof. K. Adisesha
BE, MSc, M.Tech, NET, (Ph.D.)
Data Types
Prof. K. Adisesha
Data Types
• Data Type specifies which type of value a variable can
store. type() function is used to determine a variable 's type
in Python.
• Various data types supported by Python programs are:

3
Data Types
Data Types In Python
• Booleans
• Numbers
• Strings
• Bytes
• Lists
• Tuples
• Sets
• Dictionaries

4
Data Types
Python Data objects are broadly categorized into
• Immutable Type: Those that can never change values
in place
 Number
 String
 Boolean
 Tuple
• Mutable Types: Those whose values can be changed in
place.
 List
 Set
 Dictionary

5
Strings
String In Python
• A sequence of one or more characters enclosed within either
single quotes (‘ ')or double quotes (“ ”) is considered as
String.
• Example:
>>>str1='computer science'
>>>str #print string
• Python also supports multi-line strings which require a triple
quotation mark at the start and one at the end.
• Example
>>> str2 = """A multiline string
starts and ends with
a triple quotation mark."""
>>> str2 6
Accessing String
Index Strings in Python
• Indexing of a character is used to find and retrieve it from
the String.
• Python allows to index from the zero th position in Strings.
• But it also supports negative indexes. Index of ‘-1’ , ‘-2’
represent from the last character of the String.
• Example

7
Accessing String
Slice a String in Python
• To retrieve a range of characters in a String, we use
‘slicing operator,’ the colon ‘:’ sign.
• With the slicing operator, we define the range as [a:b].
• Print all the characters of the String starting from index ‘a’
up to index ‘b-1’. So the char at index ‘b’ is not a part of
the output.
• Example: Str1=

print (Str1[3:5]) #return a range of character ‘HO’


print (Str1[7:]) # return all characters from index 7 ‘STRING’
print (Str1[:6]) # return all characters before index 6 ‘PYTHON’

8
Accessing String
Slice a String in Python
• To retrieve a range of characters in a String, we use
‘slicing operator,’ the colon ‘:’ sign.
• With the slicing operator, we define the range as [a:b].
• Print all the characters of the String starting from index ‘a’
up to index ‘b-1’. So the char at index ‘b’ is not a part of
the output.
• Example: Str=

print (sample_str[3:5]) #return a range of character ‘HO’


print (sample_str[7:]) # return all characters from index 7 ‘STRING’
print (sample_str[:6]) # return all characters before index 6 ‘PYTHON’

9
Accessing String
Modify/Delete a String in Python
• Python Strings are by design immutable. It suggests that
once a String binds to a variable, it can’t be modified.
• If you want to update the String, then re-assign a new
String value to the same variable.
• Similarly, we cannot modify the Strings by deleting some characters
from it. Instead, we can remove the Strings altogether by using the
‘del’ command.
• Example:
Str="Python String"
del sample_str[1] # TypeError: 'str' object doesn't support item deletion
del sample_str
print (sample_str) # NameError: name 'sample_str' is not defined

10
String Operators
String Operators in Python
• Concatenation (+)
 It combines two strings into one.
 Example
var1 = 'Python'
var2 = 'String'
print (var1+var2)
Output: PythonString
• Repetition (*)
 This operator creates a new string by repeating it a given number of
times.
 Example
var1 = 'Python'
print (var1*3)
Output: PythonPythonPython 11
String Operators
String Operators in Python
• Membership (in)
 This operator returns ‘True’ value if the character is present in the
given String.
• Membership (not in)
 It returns ‘True’ value if the character is not present in the given
String.
 Example
Str1 = 'Python‘ var1 = 'Python'
print ('n' in Str1) print ('n' not in Str1)
Output: True Output: False
• Iterating (for)
 For operator can iterate through all the characters of a string.
 Example: Str1 = 'Python‘
for var in Str1: print (var, end ="")
Output: Python
12
String Formatting
String Formatting Operators in Python
• Python Escape Characters
 An Escape sequence starts with a backslash (\), which signals the compiler
to treat it differently.
 Python subsystem automatically interprets an escape sequence irrespective
of it is in a single-quoted or double-quoted Strings.
 Example:
print ("Python is a \"widely\" used language")
Output: Python is a "widely" used language
• Python Format Characters
 String ‘%’ operator issued for formatting Strings. We often use this operator
with the print() function.
 Example:
print (“Student Name: %s,\n Student Age:%d" % (‘Prajwal',16))
# Student Name: Prajwal,
# Student Age: 16
13
String Formatting
List of Escape Characters
• Here is the complete list of escape characters that are represented using
backslash
Escape Char Name
\\ Backslash (\)
\” Double-quote (“)
\a ASCII bell (BEL)
\b ASCII backspace (BS)
\f ASCII linefeed (LF)
\r Carriage Return (CR)
\t Horizontal Tab (TAB)
\v ASCII vertical tab (VT)
\xnn A character with hex value nn where n can be
anything from the range 0-9, a-f, or A-F.

14
String Formatting
List of Format Symbols
• Following is the table containing the complete list of symbols that you
can use with the ‘%’ operator.
Symbol Conversion
%c character
%s string conversion via str() before formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%f floating-point real number
%O octal integer
%X hexadecimal integer (UPPER-case letters)
%E exponential notation (with UPPER-case ‘E’)

15
String Methods
Built-in String Functions in Python
• Following is the table containing the set of built-in methods that you can
use on strings.
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
lower() Converts a string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
islower() Returns True if all characters in the string are lower case
istitle() Returns True if the string follows the rules of a title
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
16
Lists
List in Python
• It is a heterogeneous collection of items of varied data
types.
• Lists in Python can be declared by placing elements inside
square brackets separated by commas.
• It is very flexible and does not have a fixed size. Index in a
list begins with zero in Python.
• List objects are mutable.
• Example:
 List1 = ['Learn', 'Python', '2']

17
Lists
Create a list in Python
• There are multiple ways to form a list in Python.
• Subscript operator
 The square brackets [ ], separated by commas represent the
subscript operator in Python.
 Example:
• blank list L1 = []
• list of integers L2 = [10, 20, 30]
• List() constructor
 Python includes a built-in list() method constructor.
 Example:
• blank list L1 = list() #empty list
• list of integers L2 = list([1,2])
18
Lists
Methods for accessing or indexing the elements of a Python list
Index operator []
• The simplest one is to use the index operator ([ ]) to access an element
from the list has zero as the first index, so a list of size ten will have
indices from 0 to 9.
 Example: vowels = ['a','e','i','o','u']
#Accessing list elements using the index operator
print(vowels[0])
Reverse indexing
• Python enables reverse (Negative) indexing for the sequence data type.
• Indexing the list with “-1” will return the last element of the list, -2 the
second last and so on.
 Example:
vowels = ['a','e','i','o','u']
print(vowels[-1])
19
Lists
List slicing
• Python comes with a magical slice operator which returns the part of a
sequence.
• It operates on objects of different data types such as strings, tuples, and
works the same on a Python list.
• Syntax: #The Python slicing operator syntax
[start(optional):stop(optional):step(optional)]
• Example:List1 = [1, 2, 3, 4, 5, 6, 7, 8]
>>>List1[2:5]
Output: [3, 4, 5]
>>>List1[2:5:2]
Output: [3, 5]
>>> theList[2:]
Output: [3, 4, 5, 6, 7, 8]
20
Lists
Reverse a list
• It is effortless to achieve this by using a special slice syntax
(::-1).
• But please note that it is more memory intensive than an in-
place reversal.
• Reverse a list using the slice operator
 Example:
List1 = [1, 2, 3, 4, 5, 6, 7, 8]
List1[::-1]
Output:[8, 7, 6, 5, 4, 3, 2, 1]
• Reverse a list but leaving values at odd indices
List1[::-2]
Output: [8, 6, 4, 2]
21
List Methods
Built-in Python list methods
• Following is the table containing the set of built-in methods that you can
use on List.
Method Description
append() It adds a new element to the end of the list.
extend() It extends a list by adding elements from another list.
insert() It injects a new element at the desired index.
remove() It deletes the desired element from the list.
pop() It removes as well as returns an item from the given position.
clear() It flushes out all elements of a list.
count() It returns the total no. of elements passed as an argument.
sort() It orders the elements of a list in an ascending manner.
reverse() It inverts the order of the elements in a list.
copy() It performs a shallow copy of the list and returns.
len() The return value is the size of the list.
22
Tuples
Tuples in Python
• A tuple is a collection, which is ordered and unchangeable.
• Define a tuple using enclosing parentheses () having its
elements separated by commas inside.
• Tuples objects are immutable.
Create a Tuple:
• Example: Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
print(Stu_tuple)
Output: ('Prajwal', 'Sunny', 'Rekha')
The tuple() Constructor:
• It is also possible to use the tuple() constructor to make a tuple.
Example : Using the tuple() method to make a tuple:
Stu_tuple = tuple((“Prajwal”, “Sunny”, “Rekha”)) # note the double round-brackets

23
Access Tuple
Access Tuple Items:
• Indexing:
 Tuple items access by referring to the index number, inside
square brackets
Example: Print the second item in the tuple:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
print(Stu_tuple[1])
Output: Sunny
• Negative Indexing:
 Negative indexing means beginning from the end, -1 refers to
the last item, and -2 refers to the second last item etc.
Example: Print the last item of the tuple:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
print(Stu_tuple[-1])
Output: Rekha 24
Access Tuple
Tuple Length:
• To determine how many items a tuple has, use the len()
• Example: Print the number of items in the tuple:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
print(len(Stu_tuple))
Output: 3
Adding Items:
 Once a tuple is created, you cannot add items to it. Tuples are
unchangeable.
Example: You cannot add items to a tuple:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
Stu_tuple[3] = "Adi" # This will raise an error
Output: TypeError: 'tuple' object does not support item assignment

25
Access Tuple
Remove Items:
• Tuples are unchangeable, so you cannot remove items from it, but you
can delete the tuple completely:
• Example: The del keyword can delete the tuple completely:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
del Stu_tuple
print(Stu_tuple) #this will raise an error because the tuple not exists
Join Two Tuples:
 To join two or more tuples you can use the + operator.
 Example: You cannot add items to a tuple:
tuple1 = ("a", "b" , "c") tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Output: ('a', 'b', 'c', 1, 2, 3)

26
Tuple & List
Difference between Tuple & List
• The tuple and a list are some what similar as they share the
following traits.
• Tuples store a fixed set of elements and don’t allow changes
whereas the list has the provision to update its content.
• The list uses square brackets for opening and closing
whereas, and a tuple has got parentheses for the enclosure.
Example of List: Example of tuple
list=[6,9] tup=(66,99)
list[0]=55 Tup[0]=3 # error message will be displayed
print(list[0]) print(tup[0])
print(list[1]) print(tup[1])
OUTPUT OUTPUT
55, 9 66, 9

27
Need for Tuple
Why need a Tuple as one of the Python data types?
• Here are a couple of thoughts in support of tuples.
• Python uses tuples to return multiple values from a
function.
• Tuples are more lightweight than lists.
• It works as a single container to stuff multiple things.
• We can use them as a key in a dictionary.

28
Tuple
Modify/Update a tuple in Python
• Since tuples are immutable, so it seems no way to modify
them.
• Once you assign a set of elements to a tuple, Python won’t
allow it to change. But, there is a catch, what if the items
you set are modifiable.
• If there is such a case, then you can change the elements
instead of directly modifying the tuple.

29
Sets
Set In Python
• Amongst all the Python data types, the set is one which supports
mathematical operations like union, intersection, symmetric
difference etc.
• A set is an unordered collection of unique and immutable objects.
• Its definition starts with enclosing braces { } having its items
separated by commas inside.
• To create a set, call the built-in set() function with a sequence or
any inerrable object.
• Example:
set1={11,22,33,22}
print(set1)
• Output
{33, 11, 22}
30
Dictionaries
Dictionary In Python
• A dictionary in Python is an unordered collection of key-
value pairs.
• It’s a built-in mapping type in Python where keys map to
values.
• Python syntax for creating dictionaries use braces {} where
each item appears as a pair of keys and values.
• Syntax:
dict = {'key1': 'value1','key2': 'value2','key3': 'value3'…'keyn': 'valuen'}
• Example:
dictr = {'Name': Sunny', 'Age': 16, 'Place': 'Bangalore'}

31
Dictionaries
Properties of Dictionary Keys
• There are two important points while using dictionary keys
• More than one entry per key is not allowed ( no duplicate
key is allowed)
• The values in the dictionary can be of any type while the
keys must be immutable like numbers, tuples or strings.
• Dictionary keys are case sensitive- Same key name but with
the different case are treated as different keys in Python
dictionaries.

32
Dictionaries
Dictionary Creation
• The function dict( ) is used to create a new dictionary with no items.
• This function is called built-in function. We can also create dictionary
using {}.
• Example: D=dict()
print D
Output: {} #{} represents empty string.
Initializing dictionary
• To add an item to the dictionary, use square brackets for
accessing and initializing dictionary values.
• Example: H=dict()
H["one"]="keyboard"
H["two"]="Mouse"
print H
Output: {'two': 'Mouse', 'one': 'keyboard'} 33
Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary


setdefault() If the key does not exist: insert the key, with the
specified value
34
Control Structure

Prof. K. Adisesha
Python Conditions
• The use of conditional programming constructs such as decision-making
statements.
• A bare Python conditional statement evaluates whether an expression is
True or False
• Some of these decision-making statements used in Python are:
 if Statement

 if Else Statement

 if-Elif-Else Statement

 Nested If-Else Statement

 Using Not Operator with If Else

 Using In Operator with If Else

36
if Statement
• 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."

37
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 University!"
else:
print "Your application is denied."

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


if condition:
statements
elif condition:
statements
else:
statements 38
Short Hand If ... Else
If you have only one statement to execute, one for if, and
one for else, you can put it all on the same line:
• Example: One line if else statement:
a=2
b = 330
print("A") if a > b else print("B")
Output: B
We have multiple else statements on the same line:
• Example: One line if else statement, with 3 conditions:

a = 330
b = 330
Print("A") if a > b else print(“equ") if a == b else print("B")
Output: equ
39
Repetition (loops)
• Iterations/ loop is the most preferred control flow statement
to be used in a Python program.
• It is used when a set of statements are to be executed to a
known or unknown total number of times.
• Most commonly used control flow statement in a Python
are:
 while loop

 For Loop

 Range() function with For Loop

 Else Clause with For loop

40
while
while loop
• A while loop is a control flow structure which repeatedly executes a
block of code indefinite no. of times until the given condition becomes
false.
• Syntax:
while condition (or expression) :
a block of code
• Example:
number = 1
while number < 200:
print number,
number = number * 2
Output:
1 2 4 8 16 32 64 128
41
The for loop
for loop
• A “for” loop is the most preferred control flow statement to be used when
you know the total no. of iterations required for execution.
• A for loop in Python requires at least two variables to work.
 The first is the iterable object such as a list, tuple or a string.
 Second is the variable to store the successive values from the sequence
in the loop.
• Syntax:
for iter in sequence:
statements(iter)
Example:
vowels="AEIOU"
for iter in vowels:
print("char:", iter)

42
range
range() function
• The range() function can produce an integer sequence at runtime.
• Syntax:
 range(start, stop) - the integers between start and stop
• Example
 range(0, 10) #will generate a series of ten integers starting from 0 to 9.

• Let’s now use the range() with a “for” loop.


• Example:
for iter in range(0, 3):
print("iter: %d" % (iter))
Output:
iter: 0
iter: 1
iter: 2

43
For Loop with Else
For Loop with Else
• Python allows using an optional else statement along with the “for” loop
• The code under the else clause executes after the completion of the
“for” loop.
• However, if the loop stops due to a “break” call, then it’ll skip the “else”
clause.
• Syntax:
for item in seq:
statement 1
statement 2
if <cond>:
break
else:
statements” loop.

44
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

45
The break Statement
break Statement
• With the break statement we can stop the loop before it has
looped through all the items
Example: Exit loop when x is “banana” Example: Do not print banana

fruits = ["apple", "banana", "cherry"] fruits = ["apple", "banana", "cherry"]


for x in fruits: for x in fruits:
print(x) if x == "banana":
if x == "banana": break
break print(x)

Output:
Output: apple
apple
banana

46
continue Statement
• With the continue statement we can stop the current
iteration of the loop, and continue with the next
Example: Do not print banana

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
continue
print(x)

Output:
apple
cherry

47
Logic
• Many logical expressions use relational operators:
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= does not equal 3.2 != 2.5 True
< less than 10 < 5 False
> greater than 10 > 5 True
<= less than or equal to 126 <= 100 False
>= greater than or equal to 5.0 >= 5.0 True

• Logical expressions can be combined with logical operators:


Operator Example Result
and 9 != 6 and 2 < 3 True
or 2 == 3 or -1 < 5 True
not not 7 > 0 False

48
Python Functions

Prof. K. Adisesha
Python Functions
Python Functions
• A function is an independent and reusable block of code which you can
call any number of times from any place in a program.
• It is an essential tool for programmers to split a big project into smaller
modules.
• A function in Python is a logical unit of code containing a sequence of
statements indented under a name given using the “def” keyword.
Creating a Function
In Python a function is defined using the def keyword:
• Syntax:
def fn(arg1, arg2,...):
"""docstring"""
statement1
statement2

50
Python Lambda
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments, but can
only have one expression.
• The power of lambda is better shown when you use them as an
anonymous function inside another function.
Syntax:
lambda arguments : expression
The expression is executed and the result is returned:
Example:
• A lambda function that adds 10 to the number passed in as an
argument, and print the result
x = lambda a : a + 10
print(x(5))

Output:15

51

You might also like