You are on page 1of 172

PYTHON PROGRAMMING

Lekha A
Computer Applications
PYTHON PROGRAMMING

Types and Operators


Python Object Types

Lekha A
Computer Applications
PYTHON PROGRAMMING
Why to use Built-in Types

• Built-in objects make programs easy to write.

• For simple tasks, built-in types are often all that is needed

to represent the structure of problem domains.

• Powerful tools such as collections (lists) and search tables

(dictionaries) are present.


PYTHON PROGRAMMING
Why to use Built-in Types

• Built-in objects are components of extensions.

• For more complex tasks, there may be a need to provide

own objects using Python classes or C language interfaces.

• Objects implemented manually are often built on top of

built-in types such as lists and dictionaries.


PYTHON PROGRAMMING
Why to use Built-in Types

• Built-in objects are components of extensions.

• For more complex tasks, there may be a need to provide

own objects using Python classes or C language interfaces.

• Objects implemented manually are often built on top of

built-in types such as lists and dictionaries.


PYTHON PROGRAMMING
Why to use Built-in Types

• Built-in objects are often more efficient than custom data

structures.

• Python’s built-in types employ already optimized data

structure algorithms that are implemented in C for speed.


PYTHON PROGRAMMING
Why to use Built-in Types

• Built-in objects are a standard part of the language.

• Python borrows both from languages that rely on built-in

tools and languages that rely on the programmer to

provide tool implementations or frameworks of their own

(e.g., C++).

• Because Python’s built-ins are standard, they’re always the

same.
PYTHON PROGRAMMING
Literals

• Numeric Literals are immutable (unchangeable).

• Numeric literals can belong to 3 different numerical types

• Integer

• Float

• Complex
PYTHON PROGRAMMING
Numeric Literals
PYTHON PROGRAMMING
String Literals

• A string literal is a sequence of characters surrounded by

quotes.

• Single, double or triple quotes are used for a string.

• A character literal is a single character surrounded by single or

double quotes.
PYTHON PROGRAMMING
String Literals
PYTHON PROGRAMMING
Boolean Literals

• A Boolean literal can have any of the two values

• True

• False
PYTHON PROGRAMMING
Special Literals

• Python contains one special literal i.e. None.

• It is used to specify to that field that is not created.


PYTHON PROGRAMMING
Datatypes

• Numbers

• List

• Tuple

• Strings

• Set

• Dictionary
PYTHON PROGRAMMING
Data types - Numbers

• Integers – int

• Integers can be of any length, it is only limited by the

memory available.
PYTHON PROGRAMMING
Data types - Numbers

• Floating point numbers – float

• A floating point number is accurate up to 15 decimal

places.

• Integer and floating points are separated by decimal

points. 1 is integer, 1.0 is floating point number.


PYTHON PROGRAMMING
Data types - Numbers

• Complex numbers - complex

• Complex numbers are written in the form, x + yj, where x is

the real part and y is the imaginary part.


PYTHON PROGRAMMING
Data types - Strings

• String is sequence of Unicode characters.

• Single quotes or double quotes can be used to represent

strings.

• Multi-line strings can be denoted using triple quotes, ''' or """.


PYTHON PROGRAMMING
Data types - Strings

• Strings can be indexed - often synonymously called

subscripted as well.

• Similar to C, the first character of a string has the index 0.


PYTHON PROGRAMMING
Data types - Tuples

• Tuple is an ordered sequence of items.

• The only difference is that tuples are immutable.

• Tuples once created cannot be modified.

• Tuples are used to write-protect data and are usually faster

than list as it cannot change dynamically.

• It is defined within parentheses () where items are separated

by commas.
PYTHON PROGRAMMING
Data types - Sets

• Set is an unordered collection of unique items.

• Set is defined by values separated by comma inside braces { }.

• Items in a set are not ordered.


PYTHON PROGRAMMING
Data types - Lists

• List is an ordered sequence of items.

• It is one of the most used datatype in Python and is very

flexible.

• All the items in a list do not need to be of the same type.

• Declaring a list is pretty straight forward.

• Items separated by commas are enclosed within brackets [

].
PYTHON PROGRAMMING
Data types - Dictionary

• A dictionary is a collection which is unordered, changeable and

indexed.

• Dictionaries are written with curly brackets.

• They have keys and values.


PYTHON PROGRAMMING
Examples of built-in functions

• The built-in function type provides type information for all

objects with standard and built-in types as well as for newly

created classes and objects.

• type(a)
PYTHON PROGRAMMING
Examples of built-in functions

• The built-in function id accepts a single parameter and returns

the identity of an object.

• id(a)
PYTHON PROGRAMMING
Examples of built-in functions

• To get the number of bits needed to represent the int object in

memory use the method bit_length()

• a.bit_length()
PYTHON PROGRAMMING
Examples of built-in functions

• To return a pair of integers whose ratio is exactly equal to the

original float and with a positive denominator use

as_integer_ratio()
PYTHON PROGRAMMING
Conversion or Casting

• In Implicit type conversion, Python automatically converts one

data type to another data type.

• Python promotes conversion of lower datatype (integer) to

higher data type (float) to avoid data loss.


PYTHON PROGRAMMING
Conversion or Casting

• Python is an object-orientated language, and as such it uses

classes to define data types, including its primitive types.

• Explicit casting in python is therefore done using constructor

functions:

• int()

• float()

• str().
PYTHON PROGRAMMING
Conversion or Casting

• int()

• Constructs an integer number from

• An integer literal

• A float literal (by rounding down to the previous whole

number) literal

• String literal (providing the string represents a whole

number)
PYTHON PROGRAMMING
Conversion or Casting
PYTHON PROGRAMMING
Conversion or Casting

• float()

• Constructs a float number from

• An integer literal

• A float literal

• A string literal (providing the string represents a float

or an integer)
PYTHON PROGRAMMING
Conversion or Casting
PYTHON PROGRAMMING
Conversion or Casting

• str()

• Constructs a string from a wide variety of data types

including

• Strings

• Integer literals

• Float literals
PYTHON PROGRAMMING
Conversion or Casting
PYTHON PROGRAMMING
Conversion or Casting

• List()

• Tuple()

• Set()

• Constructs a list, tuple, set from strings


PYTHON PROGRAMMING
Conversion or Casting

• Dict()

• Constructs a dictionary nested from a list, tuple, set


PYTHON PROGRAMMING
Conversion or Casting – Key points

• Implicit Type Conversion is automatically performed by the

Python interpreter.

• Python avoids the loss of data in Implicit Type Conversion.


PYTHON PROGRAMMING
Conversion or Casting – Key Points

• Explicit Type Conversion is also called Type Casting, the data

types of object are converted using predefined function by

user.

• In Explicit type casting loss of data may occur as the object is

enforced to a specific data type


PYTHON PROGRAMMING
Working with Strings

• Slice Operator – [] with subscript 0 for beginning of the string

and -1 for the end.

• slice(start, stop, step)

• start - starting integer where the slicing of the object

starts

• stop - integer until which the slicing takes place. The

slicing stops at index stop - 1.


PYTHON PROGRAMMING
Working with Strings

• step - integer value which determines the increment

between each index for slicing

• If a single parameter is passed, start and step are set to None.

• slice() returns a slice object used to slice a sequence in the

given indices.
PYTHON PROGRAMMING
Working with Strings
PYTHON PROGRAMMING
Working with Strings

• The plus ( + ) sign is the string concatenation operator

• str1+str2
PYTHON PROGRAMMING
Working with Strings

• The asterisk ( * ) is the repetition operator.

• str1 * 3
PYTHON PROGRAMMING
Working with Strings

• The [x : y] allows the string to be displayed from ‘x’ position till

‘y’ position are displayed and not including ‘y’ position.

• Characters inside the string cannot be changed.


PYTHON PROGRAMMING
Working with Strings

• strip() removes any whitespace from the beginning or the end.

• string.strip()
PYTHON PROGRAMMING
Working with Strings

• len() method returns the length of a string.

• len(string)
PYTHON PROGRAMMING
Working with Strings

• lower() method returns the string in lower case.

• upper() method returns the string in upper case.

• string.lower() or string.upper()
PYTHON PROGRAMMING
Working with Strings

• replace() method replaces a string with another string.

• string.replace(“character to be replaced", “character that

replaces”)
PYTHON PROGRAMMING
Working with Strings

• split() method splits the string into substrings if it finds

instances of the separator.

• string.split(“sep")
PYTHON PROGRAMMING
Working with Strings

• capitalize() converts the first character to upper case.

• string.capitalize()
PYTHON PROGRAMMING
Working with Strings

• count() returns the number of times a specified value occurs in

a string

• string.count(“Pattern”)
PYTHON PROGRAMMING
Working with Strings

• find() searches the string for a specified value and returns the

position of where it was found first

• string.find(“pattern”)
PYTHON PROGRAMMING
Working with Strings

• islower() returns True if all characters in the string are lower

case

• isupper() returns True if all characters in the string are upper

case

• string.islower() and string.isupper()


PYTHON PROGRAMMING
Lists

• One of the most obvious and useful ways to organize data is as

a list.

• Lists is used in everyday lives— shopping lists, to-do lists, and

mental checklists.
PYTHON PROGRAMMING
Lists

• Lists also occur in nature.

• Our DNA is essentially a long list of molecules in the form This Photo by Unknown Author is
licensed under CC BY-ND

of a double helix, found in the nucleus of all human cells

and all living organisms.

• Its purpose is also to store information—specifically, the

instructions that are used to construct all other cells in the

body—that we call genes .


PYTHON PROGRAMMING
Lists

• Given the 2.85 billion nucleotides that make up the human

genome, determining their sequencing (and thus

understanding our genetic makeup) is fundamentally a

computational problem.
PYTHON PROGRAMMING
Lists
PYTHON PROGRAMMING
Lists

• A list in Python is a mutable, linear data structure of variable

length, allowing mixed-type elements.

• By mutable it is meant that the contents of the list may be

altered.

• Lists in Python use zero-based indexing.

• Thus, all lists have index values 0..n-1, where n is the number

of elements in the list.


PYTHON PROGRAMMING
Lists

• A list is a linear data structure, meaning that its elements have

a linear ordering.

• An example of a list is sequence of daily temperatures for a

given week:

• The location at index 0 stores the temperature for Sunday, the

location at index 1 stored the temperature for Monday, and so

on.
PYTHON PROGRAMMING
Lists

• It is customary in programming languages to begin

numbering sequences of items with an index value of 0

rather than 1.

• This is referred to as zero-based indexing.


PYTHON PROGRAMMING
Lists

• A list traversal is a means of accessing, one-by-one, each

element of a list.

• List traversal may be used, for example, to:

• search for a particular item in a list

• add up all the elements of a list


PYTHON PROGRAMMING
Properties of Lists

• It has 0 or more elements.

• There is no name for each element.

• The size of the list is not fixed.

• The elements of the list need not be of the same type.


PYTHON PROGRAMMING
Lists

• Operations commonly performed on lists include:

• Access (retrieve)

• Update

• Append

• Insert

• Delete (remove)
PYTHON PROGRAMMING
Lists
PYTHON PROGRAMMING
Lists - Operations

• Lists are denoted by a comma-separated list of elements

within square brackets,

• [1, 2, 3] ['one', 'two', 'three'] ['apples', 50, True]

• An empty list is denoted by an empty pair of square brackets,

[].
PYTHON PROGRAMMING
Lists - Operations

• Elements of a list are accessed by use of an index value within

square brackets,

• For lst = [1, 2, 3],

• lst[0]  1 access of first element


PYTHON PROGRAMMING
Lists - Creation

• Lists are created using the list() constructor.

• list([iterable])

• iterable (optional) - an object that could be a sequence

(string, tuples) or collection (set, dictionary) or any

iterator object
PYTHON PROGRAMMING
Lists - Creation

• If no parameters are passed, it returns an empty list

• If iterable is passed as a parameter, it creates a list consisting

of iterable's items.
PYTHON PROGRAMMING
Lists - Operations

• Elements of a list are accessed by use of an index value within

square brackets,

• For lst = [1, 2, 3],

• lst[0]  1 access of first element


PYTHON PROGRAMMING
Lists - Operations

• To update, lst[2] = 4

• To delete, del lst[2]

• To insert, lst.insert(1,3)

• To append, lst.append(4)

• To remove from end, lst.pop()

• To remove from a particular position, lst.pop(10)

• To remove based on value , lst.remove(10)


PYTHON PROGRAMMING
Lists - Operations

• To check whether an element exists, ele in lst

• To find the position of an element, lst.index(10)

• To count the number of occurrences, lst.count(10)

• To sort the elements, lst.sort()


PYTHON PROGRAMMING
Assignment of Lists

• Because of the way that lists are represented in Python, when

a variable is assigned to another variable holding a list,

• e.g.,

• list2 = list1

• each variable ends up referring to the same instance of the list

in memory.
PYTHON PROGRAMMING
Assignment of Lists

• For example, if an element of list1 is changed, then the

corresponding element of list2 will change as well.

• This issue does not apply to strings and tuples, since they are

immutable, and therefore cannot be modified.


PYTHON PROGRAMMING
Copy of Lists

• When needed, a copy of a list can be made as given below,

• list3 = list(list1)

• It is not the same as list1.

• i.e. if changes are made in list1 or list3 it is not reflected in

the other.
PYTHON PROGRAMMING
Slice of Lists

• The slice object is used to slice a given sequence (string, bytes,

tuple, list or range).

• Slice object represents the indices specified by range(start,

stop, step).
PYTHON PROGRAMMING
Slice of Lists - Output

• What is the output of the following statements if n = [1, 2, 3, 4,

5, 6, 7, 8]

• print(n[-4:-1])

• print(n[-1:-4])

• print(n[-5:])

• print(n[-6:-2:2])

• print(n[::-1])
PYTHON PROGRAMMING
Tuples

• A tuple is an immutable linear data structure.

• Thus, in contrast to lists, once a tuple is defined it cannot be

altered.

• Otherwise, tuples and lists are essentially the same.


PYTHON PROGRAMMING
Tuples

• Tuples can be created in multiple ways.

• Var = val1, val2, val3

• Var=tuple((iterables))

• The inner parenthesis can be [] or {}

• Another difference of tuples and lists is that tuples of one

element must include a comma following the element.


PYTHON PROGRAMMING
Tuples

• The parenthesized element will not be made into a tuple,

as shown below,

• CORRECT WRONG

• >>> (1,) >>>(1)

• (1) 1
PYTHON PROGRAMMING
Tuples

• Any attempt to alter a tuple is invalid.

• Thus, delete, update, insert and append operations are not

defined on tuples.
PYTHON PROGRAMMING
Sets

• A set is a data structure with zero or more elements with the

following attributes.

• Elements are unique

• Does not support repeated elements


PYTHON PROGRAMMING
Sets

• Elements should be hashable

• Hashing is a mechanism to convert the given element

to an integer.

• In some storage area, at that location indicated by

hashing, the element will be stored in some way.

• Set is not ordered

• The order of elements in a set cannot be assumed.


PYTHON PROGRAMMING
Sets

• Set is an iterable

• Set cannot be indexed.

• The set is iterable, but is not a sequence.

• The membership can be checked using the in operator.

• This would be faster in case of a set compared to a list,

a tuple or a string.
PYTHON PROGRAMMING
Sets

• Sets support many mathematical operations on sets.

• Membership : in

• Union : |

• Intersection : &

• Set difference : -

• Symmetric difference : ^
PYTHON PROGRAMMING
Sets

• Sets support many mathematical operations on sets.

• Equality and inequality : = !=

• Subset and Superset : < <= > >=


PYTHON PROGRAMMING
Sets

• Set constructor { … }

• To create an empty set, the set constructor set() should be

used and not { }.


PYTHON PROGRAMMING
Sequence

• A sequence in Python is a linearly-ordered set of elements

accessed by index number.

• Lists, tuples and strings are all sequences.

• Strings, like tuples, are immutable, therefore they cannot be

altered.
PYTHON PROGRAMMING
Sequence
PYTHON PROGRAMMING
Nested Lists and Tuples

• Lists and tuples can contain elements of any type, including

other sequences.

• Thus, lists and tuples can be nested to create arbitrarily

complex data structures.


PYTHON PROGRAMMING
Nested Lists and Tuples

• This list stores three exam grades for each student.

• class_grades[0] equals [85, 91, 89]

• class_grades[1] equals [78, 81, 86]


PYTHON PROGRAMMING
Nested Lists and Tuples

• To access the first exam grade of the first student in the list,

• student1_grades = class_grades[0] 

[85, 91, 89]

• student1_exam1 = student1_grades[0] 

85

• OR

• class_grades[0][0]  8
PYTHON PROGRAMMING
Dictionary Methods

Method Description Syntax

clear() Removes all the d.clear()


elements from the
dictionary

copy() Returns a copy of the d.copy()


dictionary

fromkeys() Returns a dictionary with dict.fromkeys(x,y)


the specified keys and
value
PYTHON PROGRAMMING
Dictionary Methods

Method Description Syntax

get() Returns the value of the d.get(keyname)


specified key

items() Returns a list containing d.items()


a tuple for each key
value pair

keys() Returns a list containing d.keys()


the dictionary's keys
PYTHON PROGRAMMING
Dictionary Methods

Method Description Syntax

pop() Removes the element d.pop(keyname)


with the specified key

popitem() Removes the last d.popitem()


inserted key-value pair
PYTHON PROGRAMMING
Dictionary Methods

Method Description Syntax

setdefault() Returns the value of the d.setdefault(keyname,


specified key. If the key value)
does not exist: insert the
key, with the specified
value
PYTHON PROGRAMMING
Dictionary Methods

Method Description Syntax

update() Updates the dictionary d.update(keyname:value)

with the specified key-

value pairs

values() Returns a list of all the d.values()

values in the dictionary


PYTHON PROGRAMMING
Operators

• Arithmetic operators

• Assignment operators

• Comparison operators

• Logical operators

• Identity operators

• Membership operators

• Bitwise operators
PYTHON PROGRAMMING
Arithmetic Operators

• + Addition x+y

• - Subtraction x-y

• * Multiplication x * y

• / Division x/y

• % Modulus x%y

• ** Exponentiation x ** y

• // Floor division x // y
PYTHON PROGRAMMING
Assignment Operators

= x=5 x=5 += x += 5 x = x + 5

-= x -= 5 x = x - 5 *= x *= 5 x = x * 5

/= x /= 5 x = x / 5 %= x %= 5 x = x % 5

//= x //= 5 x = x // 5 **= x **= 5 x = x ** 5

&= x &= 5 x = x & 5 |= x |= 5 x = x | 5

^= x ^= 5 x = x ^ 5 >>= x >>= 5 x = x >> 5

<<= x <<= 5 x = x << 5


PYTHON PROGRAMMING
Comparison Operators

• Comparison operators are used to compare values.

• It either returns True or False according to the condition.


PYTHON PROGRAMMING
Comparison Operators

• > Greater that - True if left operand is greater than the right

• < Less that - True if left operand is less than the right

• == Equal to - True if both operands are equal

• != Not equal to - True if operands are not equal


PYTHON PROGRAMMING
Comparison Operators

• >= Greater than or equal to - True if left operand is greater

than or equal to the right

• <= Less than or equal to - True if left operand is less than or

equal to the right


PYTHON PROGRAMMING
Logical Operators

• and True if both the operands are true x and y

• or True if either of the operands is true x or y

• not True if operand is false (complements the operand) not x


PYTHON PROGRAMMING
Bitwise Operators

• Bitwise operators act on operands as if they were string of

binary digits.

• & Bitwise AND x& y = 0 (0000 0000)

• | Bitwise OR x | y = 14 (0000 1110)

• ~ Bitwise NOT ~x = -11 (1111 0101)

• ^ Bitwise XOR x ^ y = 14 (0000 1110)


PYTHON PROGRAMMING
Bitwise Operators

• >> Bitwise right shift x>> 2 = 2 (0000 0010)

• << Bitwise left shift x<< 2 = 40 (0010 1000)


PYTHON PROGRAMMING
Identity Operators

• is and is not are the identity operators in Python.

• They are used to check if two values (or variables) are located

on the same part of the memory.

• Two variables that are equal does not imply that they are

identical.
PYTHON PROGRAMMING
Identity Operators

• is True if the operands are identical (refer to the same

object) x is True

• is not True if the operands are not identical (do not refer to

the same object) x is not True


PYTHON PROGRAMMING
Membership Operators

• in and not in are the membership operators in Python.

• They are used to test whether a value or variable is found in a

sequence.

• in True if value/variable is found in the sequence

5 in x

• not in True if value/variable is not found in the sequence

5 not in x
PYTHON PROGRAMMING
Accessing through index

• The [x : y : z] allows the sequence to be displayed from ‘x’

position till ‘y’ number of elements are displayed skipping

every ‘z’ number of elements.

• The [x : y] allows the tuple values to be displayed from ‘x’

position till ‘y’ number of total tuples are displayed.

• The [:y] allows the tuple values to be displayed from beginning

to y position.
PYTHON PROGRAMMING
Accessing through index

• The [x:] allows the tuple values to be displayed from x position

onwards.

• The [::z] allows the tuple values to be displayed from

beginning skipping z positions.

• The [:y:z] allows the tuple values to be displayed from

beginning till ‘y’ skipping ‘z’ positions.


PYTHON PROGRAMMING
Accessing through index

• The [x::z] allows the tuple values to be displayed from

beginning skipping ‘z’ positions.

• The[:] allows all the tuple values to be displayed.


PYTHON PROGRAMMING
Slice Method

• The slice() function returns a slice object that can use used to

slice strings, lists, tuple etc.

• slice(start, stop, step)

• start - starting integer where the slicing of the object

starts

• stop - integer until which the slicing takes place. The

slicing stops at index stop - 1.


PYTHON PROGRAMMING
Slice Method

• step - integer value which determines the increment

between each index for slicing

• If a single parameter is passed, start and step are set to None.


PYTHON PROGRAMMING
String Operators

Operators Description Syntax

+ Concatenates strings str1+str2

* Repetition ‘n’ number of str1*n


times
PYTHON PROGRAMMING
String Methods

Method Description Syntax

capitalize() Converts the first character str.capitalize()


to upper case

casefold() Converts string into lower str.casefold()


case

center() Returns a centered string str.center(number)

count() Returns the number of str.count(element)


times a specified value
occurs in a string
PYTHON PROGRAMMING
String Methods

Method Description Syntax


encode() Returns an encoded str.encode()
version of the string
endswith() Returns true if the str.endswith(element)
string ends with the
specified value
expandtabs() Sets the tab size of the str.expandtabs(number)
string
PYTHON PROGRAMMING
String Methods

Method Description Syntax

find() Searches the string for a str.find(element)

specified value and returns the


position of where it was found

format() Formats specified values in a str.format(val1,

string val2,…)

index() Searches the string for a str.index(element)

specified value and returns the


position of where it was found
PYTHON PROGRAMMING
String Methods

Method Description Syntax

isalnum() Returns True if all characters in str.isalnum()


the string are alphanumeric

isalpha() Returns True if all characters in str.isalpha()


the string are in the alphabet

isdecimal() Returns True if all characters in str.isdecimal()


the string are decimals

isdigit() Returns True if all characters in str.isdigit()


the string are digits
PYTHON PROGRAMMING
String Methods

Method Description Syntax


isidentifier() Returns True if the string str.isidentifier()
is an identifier

islower() Returns True if all str.islower()


characters in the string
are lower case
isnumeric() Returns True if all str.isnumeric()
characters in the string
are numeric
isprintable() Returns True if all str.isprintable()
characters in the string
are printable
PYTHON PROGRAMMING
String Methods

Method Description Syntax

isspace() Returns True if all characters in str.isspace()


the string are whitespaces

istitle() Returns True if the string str.istitle()

follows the rules of a title

isupper() Returns True if all characters in str.isupper()


the string are upper case

join() Joins the elements of an str.join(iterable)

iterable to the end of the string


PYTHON PROGRAMMING
String Methods

Method Description Syntax


ljust() Returns a left justified str.ljust(width)
version of the string

lower() Converts a string into lower str.lower()


case
lstrip() Returns a left trim version of str.lstrip()
the string

partition() Returns a tuple where the str.partition(element)


string is parted into three
parts
PYTHON PROGRAMMING
String Methods

Method Description Syntax

replace() Returns a string where a str.replace(val1, val2)

specified value is replaced


with a specified value

rfind() Searches the string for a str.rfind(element)

specified value and returns


the last position of where it
was found
PYTHON PROGRAMMING
String Methods

Method Description Syntax

rindex() Searches the string for a str.rindex(element)

specified value and returns


the last position of where it
was found

rjust() Returns a right justified str.rjust()

version of the string


PYTHON PROGRAMMING
String Methods

Method Description Syntax

rpartition() Returns a tuple where the str.rpartition(element)


string is parted into three
parts

rsplit() Splits the string at the str.rfind(seperator)

specified separator, and


returns a list
rstrip() Returns a right trim str.rstrip()
version of the string
PYTHON PROGRAMMING
String Methods

Method Description Syntax

split() Splits the string at the str.split(separator, max)

specified separator, and


returns a list

splitlines() Splits the string at line str.splitlines()

breaks and returns a list

startswith() Returns true if the string str.startswith(element)

starts with the specified


value
PYTHON PROGRAMMING
String Methods

Method Description Syntax

strip() Returns a trimmed str.strip()

version of the string

swapcase() Swaps cases, lower case str.swapcase()

becomes upper case and


vice versa

title() Converts the first str.title()

character of each word to


upper case
PYTHON PROGRAMMING
String Methods

Method Description Syntax

upper() Converts a string into str.upper()


upper case

zfill() Fills the string with a str.zfill(number)


specified number of 0
values at the beginning
PYTHON PROGRAMMING
List Comprehensions

• List comprehensions in Python can be used to generate

more varied sequences.

• It is a method to create lists using rules.


PYTHON PROGRAMMING
List Comprehensions

• l1 = [ 'hello' for x in range(5)]

• This statement would create a list containing hello five

times.
PYTHON PROGRAMMING
List Comprehensions

• The previous statement is equivalent to the following piece

of code.

• l1 = []

• for x in range(5):

• l1.append(x)
PYTHON PROGRAMMING
List Comprehensions

• The general form of list comprehension is

• [ <expr> for <variable> in <iterable> ]


PYTHON PROGRAMMING
List Comprehensions

• Semantically, this is equivalent the following.

• Create an empty list.

• Execute the for part of the list comprehension.

• Evaluate the expr each time.

• Append that to the list.

• The result is the list so created.


PYTHON PROGRAMMING
List Comprehensions
PYTHON PROGRAMMING
Introduction
• File is a named location on the system storage which records

data for later access.

• It enables persistent storage in a non-volatile memory i.e. Hard

disk.

• A file is a collection of data stored in one unit, identified by

a filename.

• It can be a document, picture, audio or video stream, data

library, application, or other collection of data.


PYTHON PROGRAMMING
Introduction

• The in-built methods in python can handle two major types

of files.

• The types are text files and binary files.

• The text and binary files has .txt and .bin as their

extensions respectively.
PYTHON PROGRAMMING
Introduction

• Text files are used to store human readable information

whereas the binary files contains computer readable

information that are written using binary digits 0s and 1s.


PYTHON PROGRAMMING
Introduction

• The file processing in python is done by two different types of

approaches.

• Processing the content in the file.

• Done by the built in functions

• Processing the directory.

• Processed by the os module methods.


PYTHON PROGRAMMING
Introduction

• In Python, file processing takes place in the following order.

• Open a file that returns a filehandle.

• Use the handle to perform read or write action.

• Close the filehandle.


PYTHON PROGRAMMING
Creating a file

• The method open() is used to open an existing file or creating a

new file.

• If the complete directory is not given then the file will be

created in the directory in which the python file is stored.


PYTHON PROGRAMMING
Creating a file

• file_object = open( file_name, “Access Mode”, Buffering )

• File name is a unique name in a directory.

• The open() function will create the file with the specified

name if it is not already exists otherwise it will open the

already existing file.

• The open method returns file object which can be stored in

the name file_object.


PYTHON PROGRAMMING
Creating a file

• The access mode is the string which tells in what mode the file

should be opened for operations.

• There are three different access modes are available in python.


PYTHON PROGRAMMING
Creating a file

• Reading

• Reading mode is used only for reading the file.

• The pointer will be at the beginning of the file.

• Writing

• Writing mode is used for overwriting the information on

existing file.
PYTHON PROGRAMMING
Creating a file

• Append

• Append mode is same as the writing mode.

• Instead of over writing the information this mode appends

the information at the end.


PYTHON PROGRAMMING
Creating a new file – Access Modes

• Reading Mode

• r - Opens a text file for Reading

• rb - Opens a binary file for Reading

• r+ - Opens a text file for Reading and Writing

• rb+ - Opens a binary file for Reading and Writing


PYTHON PROGRAMMING
Creating a new file – Access Modes

• Writing Mode

• w - Opens a text file for Writing

• wb - Opens a binary file for Writing

• w+ - Opens a text file for Reading and Writing

• wb+ - Opens a binary file for Reading and Writing


PYTHON PROGRAMMING
Creating a new file – Access Modes

• Append Mode

• a - Opens a text file for appending

• ab - Opens a binary file for appending

• a+ - Opens a text file for appending and reading

• ab+ - Opens a binary file for appending and reading


PYTHON PROGRAMMING
Creating a new file - Buffering

• Buffering is the process of storing a chunk of a file in a

temporary memory until the file loads completely.

• In python there are different values can be given.

• If the buffering is set to 0 , then the buffering is off.

• The buffering will be set to 1 when there is a need to

buffer the file.


PYTHON PROGRAMMING
Creating a new file - Buffering

• Buffering is the process of storing a chunk of a file in a

temporary memory until the file loads completely.

• In python there are different values can be given.

• If the buffering is set to 0 , then the buffering is off.

• The buffering will be set to 1 when there is a need to

buffer the file.


PYTHON PROGRAMMING
Creating a new file

• Create a new file in the text format.


PYTHON PROGRAMMING
Creating a new file

• Useful methods used on file object

• file.name

• Returns the name of file

• file.mode

• Returns the access mode of the file

• file.closed

• Returns true if the file is closed


PYTHON PROGRAMMING
Creating a new file


PYTHON PROGRAMMING
Creating a new file

• To use r+ the file must be present in the directory.

• Otherwise it will give some error.


PYTHON PROGRAMMING
Writing information in the file

• The write() method is used for writing a string inside a file.

• file_object.write(“String”)

• The output is the number of characters written in the file.

• The contents will be written to the file when the file is

closed.
PYTHON PROGRAMMING
Reading from a file

• The text information in the text file can be extracted with the

help of read() function.

• var_name = file_object.read(index)

• The index argument determines how many characters

to be printed from the file.


PYTHON PROGRAMMING
Reading from a file


PYTHON PROGRAMMING
Closing a file

• After processing the content in a file, the file must be saved

and closed.

• Use close() for closing the file.

• This is an important method to be remembered while handling

files in python.

• file_object.close()
PYTHON PROGRAMMING
Closing a file


PYTHON PROGRAMMING
Appending to a file

• To append access mode ‘a’ or ‘a+’ should be used.


PYTHON PROGRAMMING
File Methods

Method Description

close() Closes the file

detach() Returns the separated raw stream from the buffer

fileno() Returns a number that represents the stream, from

the operating system's perspective

flush() Flushes the internal buffer


PYTHON PROGRAMMING
File Methods

Method Description

isatty() Returns whether the file stream is interactive or

not

read() Returns the file content

readable() Returns whether the file stream can be read or not


PYTHON PROGRAMMING
File Methods

Method Description

readline() Returns one line from the file

readlines() Returns a list of lines from the file

seek() Change the file position

writelines() Writes a list of strings to the file

tell() Returns the current file position


PYTHON PROGRAMMING
File Methods

Method Description

seekable() Returns whether the file allows us to change the

file position

truncate() Resizes the file to a specified size

writable() Returns whether the file can be written to or not

write() Writes the specified string to the file


PYTHON PROGRAMMING
File Methods


PYTHON PROGRAMMING
Renaming a file

• The file name can be changed by a method rename() .

• The rename() method is available in the os module.

• Before calling the rename function import the os module

into the program.

• os.rename(old_name, new_name)
PYTHON PROGRAMMING
Renaming a file


PYTHON PROGRAMMING
Renaming a file

• To rename a file it has to be closed otherwise it will give an

error.
PYTHON PROGRAMMING
Renaming a file


PYTHON PROGRAMMING
Deleting a file

• remove() is used to delete an existing file in a directory.

• It needs to be imported from os module.

• os.remove(file_name)
PYTHON PROGRAMMING
Deleting a file
PYTHON PROGRAMMING
Deleting a file


THANK YOU

Lekha A
Department of Computer Applications
lekha@pes.edu
+91 80 6666 3333 Extn 899

You might also like