Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 40

Python3 Programming Language

Shahid Qureshi
Lists
Lists
 A list in Python is an ordered group of items or elements, and these list elements don't
have to be of the same type.
 A list contains items separated by commas and enclosed within square brackets.
 List indexes like strings starting at 0 in the beginning of the list and working their way
from -1 at the end.
 An empty list can be declared as
 somelist = [ ]
 Example
Example

 This example shows how to access, update and delete list elements:
 Similar to strings, Lists operations include slicing ([ ] and [:]) ,
 access
 slice
 update

 delete

 concatenation (+), repetition (*)


Common List Functions
Function Description
len(list) Gives the total length of the list.
max(list) Returns item from the list with max value.
min(list) Returns item from the list with min value.
sum(list) Returns the sum of all the elements

 max, min works only on list with same type of values


 sum works only on lists with numeric values
Lists
 Common List Methods
Method Description
list.append(obj) Appends object obj to list
list.pop(index) Deletes the obj at index
list.insert(index, obj) Inserts object obj into list at offset index
list.count(obj) Returns count of how many times obj occurs in list
list.index(obj) Returns the lowest index in list that obj appears
list.remove(obj) Removes object obj from list
list.reverse() Reverses objects of list in place
list.sort() Sorts objects of list in place
Deleting List elements

 pop(index)
returns the deleted values as well
 del [index]
more than one value can be deleted with del [ : ]
 remove(value)
Lists
 Lists can have sublists as elements and these sublists may contain other sublists
as well.
Python Membership Operators
 Membership operators are used to test if a sequence is presented in an
object:
Lists & Strings

 strings can be converted to lists

 split() function of string can be used for the same purpose with flexibility

 Inverse of split is also possible with join() function


list elements will be joined together with the delimiter in between
modifying a string

 string can not be modified


so we also call it immutable

 Solution
Convert to list and then modify
Python Control Structures
Conditionals

 In Python, True and False are Boolean objects of class 'bool'


 Python assumes any non-zero and non-null values as True, otherwise it is False value.
 Python does not provide switch or case statements as in other languages.
 Syntax:
if Statement if..else Statement if..elif..else Statement

 Example:
Use of logical operators
Conditionals

 Using the conditional expression


Another type of conditional structure in Python, which is very convenient and easy to read.


Loops
 The while Loop
range()

 It allows user to generate a series of numbers within a given range


range(start, stop, increment)

 There are three ways you can call range() :

 Examples
Examples
Loops

 The For Loop


Loops
Loop Control Statements
 break :Terminates the statement and transfers execution to the statement
immediately
loop following the loop.

 continue :Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating.

 Infinite Loop:
while True:
Example

 Given a string consisting of many words, store the words in a list leaving out
the duplicates

 Given two lists, find out the common items, and store them in a third list
Python Functions
Functions
 Function Syntax

 Function Arguments
You can call a function by using any of the following types of arguments:
• Required arguments: the arguments passed to the function in correct
positional order.
• Keyword arguments: the function call identifies the arguments by the
parameter names.
• Default arguments: the argument has a default value in the function
declaration used when the value is not provided in the function call.

By Tahani Almanie | CSCI 5448


Functions

• Variable-length arguments: This used when you need to process unspecified additional
arguments. An asterisk (*) is placed before the variable name in the function declaration.

By Tahani Almanie | CSCI 5448


Flow of Execution

 There is no main() function to begin with

 Program starts execution from the first line

 Functions must be defined before they are called

 Functions will only be executed, if they are called

 No pass-by-value or pass-by-ref kind of things here

 Return statement is optional

 Function can return multiple values


Variable and Reference

 In a=1, an object with value '1' is created in memory and a reference 'a'
now points to it
Immutable vs Mutable
Immutable vs Mutable

>>> a=1 >>> data = ["network", "prog"]


>>> id(a) >>> id(data)
1586324624 49222320
>>> a=2 >>> data.append("python")
>>> id(a) >>> data
1586324640 ['network', 'prog', 'python']
>>> id(data)
49222320
>>> string = "hello world"
>>> id(string)
52076936
>>> string = string + " welcome to python"
>>> string
'hello world welcome to python'
>>> id(string)
49161680
Mutable object
Python File Handling

By Tahani Almanie | CSCI 5448


File Handling

 File opening fileObject = open(file_name [, access_mode][, buffering])


Common access modes:
• “r” opens a file for reading only.
• “w” opens a file for writing only. Overwrites the file if the file exists.
Otherwise, it creates a new file.
• “a” opens a file for appending. If the file does not exist, it creates a new file
for writing.

 Closing a file fileObject.close()


The close() method flushes any unwritten information and closes the file object.

By Tahani Almanie | CSCI 5448


File Handling

 Reading a file fileObject.read([count])


• The read() method reads the whole file at once.
• The readline() method reads one line each time from the file.
• The readlines() method reads all lines from the file in a list.

 Writing in a file fileObject.write(string)


The write() method writes any string to an open file.

By Tahani Almanie | CSCI 5448


Examples: File reading

read() reads the whole file

reading line by line using for loop


Example: File writing
seek() and tell()

 seek(offset)
 sets the file’s current position
 tell()
returns the file’s current position

 these function are particularly useful when working with binary files
Python Exception Handling

By Tahani Almanie | CSCI 5448


Example
Exception Handling

 Handling an exception with a try statement is called catching an exception.


 catching an exception gives you a chance to fix the problem, or try again, or
at least end the program gracefully.
Exception Handling
 Common Exceptions in Python:
NameError - TypeError - IndexError - KeyError - Exception
 Exception Handling Syntax:

 An empty except statement can catch any exception.


 finally clause: always executed before finishing try statements.

By Tahani Almanie | CSCI 5448

You might also like