0% found this document useful (0 votes)
3 views61 pages

Python Unit 2

The document covers Python programming concepts, focusing on lists and functions, including topics such as function definitions, recursion, global variables, and list operations. It provides examples of built-in functions, list methods, and the differences between lists and tuples. Additionally, it discusses nested sequences and dictionaries as ways to organize data in Python.

Uploaded by

prajapatimeet360
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views61 pages

Python Unit 2

The document covers Python programming concepts, focusing on lists and functions, including topics such as function definitions, recursion, global variables, and list operations. It provides examples of built-in functions, list methods, and the differences between lists and tuples. Additionally, it discusses nested sequences and dictionaries as ways to organize data in Python.

Uploaded by

prajapatimeet360
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Faculty of Engineering & Technology

Sankalchand Patel College of Engineering, Visnagar

Python Programming
(1ET2070201)

Unit-02
Lists and Functions
Content
• Functions and scoping
• List Operations
• Recursion
• Global variables
• Modules
• File I/O
• In Built Functions and Parameters
• Dictionary
Math commands
from math import *
Function name Description Constant Description
abs(value) absolute value e 2.7182818...
ceil(value) rounds up pi 3.1415926...
cos(value) cosine, in radians
degrees(value) convert radians to degrees
floor(value) rounds down
log(value, base) logarithm in any base
log10(value) logarithm, base 10
max(value1, value2, ...) larger of two (or more) values
min(value1, value2, ...) smaller of two (or more) values
radians(value) convert degrees to radians
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root
tan(value) tangent
Random Numbers
from random import *
randint(min, max)
• returns a random integer in range [min, max] inclusive
choice(sequence)
• returns a randomly chosen value from the given sequence
• (the sequence can be a range, a string, an array, ...)
>>> from random import *
>>> randint(1, 5)
2
>>> randint(1, 5)
5
>>> choice(range(4, 20, 2))
16
>>> choice("hello")
'e'
Functions
• Function: Equivalent to a static method in Java.

[Link]
• Syntax:
1 # Prints a helpful message.
def name(): 2 def hello():
statement 3 print("Hello, world!")
4
statement 5 # main (calls hello twice)
... 6 hello()
7 hello()
statement

• Must be declared above the 'main' code


• Statements inside the function must be indented
Functions
• Module
• Contains function definitions and other elements
• All of which are related in some way
• Calling a function
• functionName ( argument1, argument2 )
• The import keyword is used to include a module
• Invoking functions from a module
• Use the module name followed by the dot operator (.)
• [Link]( argument )
Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> print [Link]( 900 )
30.0
>>> print [Link]( -900 )
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: math domain error
Parameters
def name(parameter, parameter, ..., parameter):
statements

• Parameters are declared by writing their names (no types)

>>> def print_many(message, n):


... for i in range(n):
... print(message)

>>> print_many("hello", 4)
hello
hello
hello
hello
Returning values
def name(parameters):
statements
...
return expression

• Python doesn't require you to declare that your function returns a value; you
just return something at its end.
>>> def ftoc(temp):
... tempc = 5.0 / 9.0 * (temp - 32)
... return tempc

>>> ftoc(98.6)
37.0
Default Parameter Values
def name(parameter=value, ..., parameter=value):
statements
• Can make parameter(s) optional by specifying a default value
>>> def print_many(message, n=1):
... for i in range(n):
... print(message)
>>> print_many("shrubbery")
shrubbery
>>> print_many("shrubbery", 3)
shrubbery
shrubbery
shrubbery
Creating Intentional Infinite Loops
• Break – breaks out of a loop
• Terminates the loop prior to the exit condition becoming false
• Continue – jump back to the top of the loop
Parameter Keywords
name(parameter=value, ..., parameter=value)
• Can specify name of each parameter as you call a function
• This allows you to pass the parameters in any order
>>> def print_many(message, n):
... for i in range(n):
... print(message)

>>> print_many(str="shrubbery", n=4)


shrubbery
shrubbery
shrubbery
shrubbery
>>> print_many(n=3, str="Ni!")
Ni!
Ni!
Ni!
Global Variables and Constants
• Rules for value retrieval
• Based on namespace and scope
• Namespaces store information about an identifier and a value to which it is
bound
• Three types
• Local, global, and built-in
• They are also checked by Python in the order listed above
• Local namespace
• Contains values that were created in a block
• Each function has a unique local namespace
Global Variables and Constants
x = 1 # global variable print ("global x is", x)
# alters the local variable x, shadows the global x=7
variable print ("global x is", x)
def a(): a()
x = 25
b()
print ("\nlocal x in a is", x, "after entering a“)
a()
x += 1
b()
print ("local x in a is", x, "before exiting a“)
print ("\nglobal x is", x)
# alters the global variable x
def b():
global x
print ("\nglobal x is", x, "on entering b“)
x *= 10
print ("global x is", x, "on exiting b“)
Global Variables and Constants
• global x is 1
• global x is 7
• local x in a is 25 after entering a
• local x in a is 26 before exiting a
• global x is 7 on entering b
• global x is 70 on exiting b
• local x in a is 25 after entering a
• local x in a is 26 before exiting a
• global x is 70 on entering b
• global x is 700 on exiting b
• global x is 700
Recursive Functions
• Recursive functions
• A function that has a call to itself
• Either directly or indirectly
• The function only knows how to solve the base case
• The base case is the simplest form of the problem
• If the function does not get the base case it breaks the problem up
• The problem is split into a solvable and non-solvable pieces
• These pieces are then passed to the function again to either be solved or
broken up more
• Original call to the function remains open
• Closes only when all sub calls are finished
Recursive Functions

# Recursive definition of function factorial • 0! = 1


def factorial( number ): • 1! = 1
• 2! = 2
if number <= 1: # base case • 3! = 6
return 1 • 4! = 24
• 5! = 120
else:
• 6! = 720
# recursive call
• 7! = 5040
return number * factorial( number - 1 ) • 8! = 40320
• 9! = 362880
for i in range( 11 ): • 10! = 3628800
print( "%2d! = %d" % ( i, factorial( i ) ))
Iteration vs. Recursion
• Iteration
• The use of loops to create repetition
• Loops infinitely if condition never evaluates to false
• Recursion
• The use of function calls to create repetition
• Loops infinitely if condition never breaks down to base case
• Repeatedly invokes the mechanism and function
• This can eat up processor time
• Uses lots of memory as well
• Copies of the function’s variables are made
Lists
• list: Python's equivalent to Java's array
• Declaring:
name = [value, value, ..., value] or,
name = [value] * length

• Accessing/modifying elements: (same as Java)


name[index] = value

>>> scores = [9, 14, 18, 19, 16]


[9, 14, 18, 19, 16]
>>> counts = [0] * 4
[0, 0, 0, 0]
>>> scores[0] + scores[4]
25
Indexing
• Lists can be indexed using positive or negative numbers:

>>> scores = [9, 14, 12, 19, 16, 7, 24, 15]


[9, 14, 12, 19, 16, 7, 24, 15]
>>> scores[3]
19
>>> scores[-3]
7

index 0 1 2 3 4 5 6 7
value 9 14 12 19 16 7 24 15
index -8 -7 -6 -5 -4 -3 -2 -1
Using Lists
• Deleting a list element
del inventory[2]

• Deleting a list slice


del inventory[4:6]
List Methods
• append(value)
• Adds value to the end of the list

• sort()
• Sorts the elements, smallest value first

• reverse()
• Reverses the order of a list

• count(value)
• Returns the number of occurences of value in the list
List Methods
• index(value)
• Returns the first position number of where value occurs

• insert(i, value)
• inserts value at position i

• pop([i])
• Returns value at position i and removes value from the list. Providing the position number is
optional. Without it, the last element in the list is removed.

• remove(value)
• Removes the first occurrence of value from the list.
Other List Abilities
• Lists can be printed (or converted to string with str()).
• Find out a list's length by passing it to the len function.
• Loop over the elements of a list using a for ... in loop.

>>> scores = [9, 14, 18, 19]


>>> print("My scores are", scores)
My scores are [9, 14, 18, 19]
>>> len(scores)
4
>>> total = 0
>>> for score in scores:
... print("next score:", score)
... total += score
next score: 9
next score: 14
next score: 18
next score: 19
>>> total
60
Ranges, Strings, and Lists
• The range function returns a list.
>>> nums = range(5)
>>> nums
[0, 1, 2, 3, 4]
>>> nums[-2:]
[3, 4]
>>> len(nums)
5

• Strings behave like lists of characters:


• len
• indexing and slicing
• for ... in loops
Tuple
tuple_name = (value, value, ..., value)
• A way of "packing" multiple values into one variable
>>> x = 3
>>> y = -5
>>> p = (x, y, 42)
>>> p
(3, -5, 42)

name, name, ..., name = tuple_name


• "unpacking" a tuple's contents into multiple variables
>>> a, b, c = p
>>> a
3
>>> b
-5
>>> c
42
Using Tuples
• Useful for storing multi-dimensional data (e.g. (x, y) points)
>>> p = (42, 79)

• Useful for returning more than one value


>>> from random import *
>>> def roll2():
... die1 = randint(1, 6)
... die2 = randint(1, 6)
... return (die1, die2)
...
>>> d1, d2 = roll2()
>>> d1
6
>>> d2
4
Tuple as Parameter
def name( (name, name, ..., name), ... ):
statements

• Declares tuple as a parameter by naming each of its pieces

>>> def slope((x1, y1), (x2, y2)):


... return (y2 - y1) / (x2 - x1)
...
>>> p1 = (2, 5)
>>> p2 = (4, 11)
>>> slope(p1, p2)
3

[Link]
Tuple as Return
def name(parameters):
statements
return (name, name, ..., name)

>>> from random import *


>>> def roll2():
... die1 = randint(1, 6)
... die2 = randint(1, 6)
... return (die1, die2)
...
>>> d1, d2 = roll2()
>>> d1
6
>>> d2
4
Tuples vs. Lists
Sno LIST TUPLE
1 Lists are mutable Tuples are immutable

The implication of iterations is


2 The implication of iterations is Time-consuming
comparatively Faster

The list is better for performing operations, such as A Tuple data type is appropriate for
3
insertion and deletion. accessing the elements

Tuple consumes less memory as


4 Lists consume more memory
compared to the list

Tuple does not have many built-in


5 Lists have several built-in methods
methods.

Unexpected changes and errors are more likely to Because tuples don’t change they are
6
occur far less error-prone.
Nested Sequences

Column 0 Column 1 Column 2 Column 3


Row 0 a[0][0] a[0][1] a[0][2] a[0][3]

Row 1 a[1][0] a[1][1] a[1][2] a[1][3]

Row 2 a[2][0] a [2][1] a[2][2] a[2][3]

Column index (or subscript)


Row index (or subscript)

Array name
Nested Sequences
• Creating nested sequences (examples)

nested_1 = [“first”, (“second”, “third”), [“fourth”, “fifth” ]]

scores = [(“Moe”, 1000),(“Larry”, 1500),(“Curly”, 2000)]

nested_2 = (“deep”,(“deeper”,(“deepest”, ”still deepest”)))


Accessing Nested Sequences
>>> scores = [(“Moe”, 1000),(“Larry”, 1500),(“Curly”, 2000)]
>>> print scores[0]
(‘Moe’, 1000)
>>> print scores[1]
(‘Larry’, 1500)
>>> print scores[2]
(‘Curly’, 2000)

>>> a_score = scores[2]


>>> print a_score
(‘Curly’, 2000)
>>> print a_score[0]
Curly

>>> print scores[2][0]


Curly
>>> print scores[2][0][4]
y
Dictionaries
• Programmers love to organize information
• Lists and tuples organize things into sequences

• Dictionaries stores information in pairs


• Similar to an actual dictionary
• Word and definition
• Python uses key and value
Dictionaries
• Mapping constructs consisting of key-value pairs
• Referred to as hashes in other languages
• Unordered collection of references
• Each value is referenced though key in the pair
• Curley braces ({}) are used to create a dictionary
• When entering values
• Use { key1:value1, … }
• Keys must be immutable values such as strings, numbers and tuples
• Values can be of any Python data type
Dictionaries
# create and print an empty dictionary
grades[ "Michael" ] = 93
emptyDictionary = {}
print ("\nDictionary grades
print ("The value of emptyDictionary is:",
after modification:“)
emptyDictionary) # create and print a
print (grades)
dictionary with initial values
# delete entry from dictionary
grades = { "John": 87, "Steve": 76, "Laura": 92,
del grades[ "John" ]
"Edwin": 89 }
print ("\nDictionary grades
print ("\nAll grades:", grades) after deletion:“) print
# access and modify an existing dictionary (grades)
print ("\nSteve's current grade:", grades[
"Steve" ])
grades[ "Steve" ] = 90
print ("Steve's new grade:", grades[ "Steve" ])
# add to an existing dictionary
Dictionaries
The value of emptyDictionary is: {}

All grades: {'Edwin': 89, 'John': 87, 'Steve': 76, 'Laura': 92}

Steve's current grade: 76


Steve's new grade: 90

Dictionary grades after modification:


{'Edwin': 89, 'Michael': 93, 'John': 87, 'Steve': 90, 'Laura': 92}

Dictionary grades after deletion:


{'Edwin': 89, 'Michael': 93, 'Steve': 90, 'Laura': 92}
Dictionaries
Met ho d De sc rip tio n

clear() Deletes all items from the dictionary.

copy() Creates and returns a shallow copy of the dictionary (the


elements in the new dictionary are references to the
elements in the original dictionary).
get( key [, returnValue] ) Returns the value associated with key. If key is not in the
dictionary and if returnValue is specified, returns
the specified value. If returnValue is not specified,
returns None.

has_key( key ) Returns 1 if key is in the dictionary; returns 0 if key is


not in the dictionary.
items() Returns a list of tuples that are key-value pairs.

keys() Returns a list of keys in the dictionary.

popitem() Removes and returns an arbitrary key-value pair as a


tuple of two elements. If dictionary is empty, a Key-
Error exception occurs. [Note: We discuss
exceptions in Chapter 12, Exception Handling.] This
method is useful for accessing an element (i.e., print the
key-value pair) before removing it from the dictionary.
Dictionaries
setdefault( key [, Behaves similarly to method get. If key is not
dummyValue] ) in the dictionary and dummyValue is specified, inserts
the key and the specified value into dictionary. If
dummyValue is not specified, value is
None.
update( newDictionary Adds all key-value pairs from newDictionary to the
current dictionary and overrides the values for keys that
) already exist.
values() Returns a list of values in the dictionary.
Dictionaries
>>> dictionary = { "listKey" : [ 1, 2, 3 ] }
>>> shallowCopy = [Link]() # make a shallow copy
>>> dictionary[ "listKey" ].append( 4 )
>>> print (dictionary)
{'listKey': [1, 2, 3, 4]}
>>> print (shallowCopy)
{'listKey': [1, 2, 3, 4]}

>>> from copy import deepcopy # make a deep copy


>>> deepCopy = deepcopy( dictionary )
>>> dictionary[ "listKey" ].append( 5 )
>>> print (dictionary)
{'listKey': [1, 2, 3, 4, 5]}
>>> print (shallowCopy)
{'listKey': [1, 2, 3, 4, 5]}
>>> print (deepCopy)
{'listKey': [1, 2, 3, 4]}
Dictionaries
monthsDictionary = { 1 : "January", 2 : "February", 3 : "March",
4 : "April", 5 : "May", 6 : "June", 7 : "July",
8 : "August", 9 : "September", 10 : "October",
11 : "November", 12 : "December" }
print ("The dictionary items are:“)
print ([Link]( ))
print ("\nThe dictionary keys are:“)
print ([Link]( ))
print ("\nThe dictionary values are:“)
print ([Link]( ))
print ("\nUsing a for loop to get dictionary items:“)
for key in [Link]( ):
print ("monthsDictionary[", key, "] =", monthsDictionary[ key ])
Dictionaries
The dictionary items are:
[(1, 'January'), (2, 'February'), (3, 'March'), (4, 'April'), (5, 'May'), (6, 'June'), (7, 'July'), (8, 'August'), (9, 'September'), (10, 'October'), (11, 'November'), (12, 'December')]
The dictionary keys are:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
The dictionary values are:
['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
Using a for loop to get dictionary items:
monthsDictionary[ 1 ] = January
monthsDictionary[ 2 ] = February
monthsDictionary[ 3 ] = March
monthsDictionary[ 4 ] = April
monthsDictionary[ 5 ] = May
monthsDictionary[ 6 ] = June
monthsDictionary[ 7 ] = July
monthsDictionary[ 8 ] = August
monthsDictionary[ 9 ] = September
monthsDictionary[ 10 ] = October
monthsDictionary[ 11 ] = November
monthsDictionary[ 12 ] = December
Reading From Text Files
• Secondary storage is the computer’s hardware unit for the long term
storage of data.
• Hard disks are the most popular, but tapes, floppy disks, CF cards, and
USB drives are other hardware devices for storing data persistently.
• A file is a sequence of characters stored on a disk drive. Files have a
name and an optional file extension.
Reading From Text Files
• Opening and closing a text file
• Files have to be opened before a program can read (write) data from it
• Syntax
any_file = open( “[Link]”, “r” )
• Files also have to be closed when a program is finished with it
• Syntax
any_file.close()
Reading From Text Files
• Opening and closing a text file
• The file subdirectory path may have to be included in the file name
any_file = open( “c:\ICP10061\exams\[Link]”, “r” )
• The “r” is called the “access mode”
• r is for reading
• if the file does not exist, an error is raised
• w is for writing
• If the file exists, the contents are overwritten. If the file does not exist, it will be created
• a is for appending
• If the file exists new data is appended to the end of the file. If the file does not exist, it will be
created
• others listed in the text book
Reading From Text Files
• Reading characters from a text file
• There are several functions and methods for reading data from a file

• The read() method allows a program to read a specified number of characters


from a file and returns them as a string

• Example
any_file = open( “[Link]”, “r” )
print any_file.read(5)
print any_file.read(4)
any_file.close()

• Python remembers where the file last read data by using a “file pointer” or
“bookmark”
Reading From Text Files
• Reading characters from a text file
• All files have a “end of file” indicator (EOF) that signals to your program that
there is no more data to read in a file
• Trying to read past the end of the file will return an empty string
• Example
any_file = open( “[Link]”, “r” )
all_the_data = any_file.read()
any_file.close()
Reading From Text Files
• Reading characters from a line
• Text files are often line oriented and your program may have to read and
process one line at a time
• The method read_line() is used to read characters from the current line only
• Example
anystring = any_file.readline(1)
anystring = any_file.readline(5)
anystring = any_file.readline()
Reading From Text Files
• Reading all lines into a list
• Another way to work with lines from a file is to read each line (string) into a
list
• The method read_lines() is used to read all the lines from a text file and store
them into a list of lines (strings)
• Example
any_list = any_file.readlines()
Reading From Text Files
• Looping through a text files
• Text files are a type of sequence delimited by lines
• Python programs can also read and process lines from text files by using
iteration
• Example
for line in any_file:
print line
Reading Files
name = open("filename")
• opens the given file for reading, and returns a file object

[Link]() - file's entire contents as a string

[Link]() - next line from file as a string


- file's contents as a list of lines
[Link]()
• the lines from a file object can also be read using a for loop

>>> f = open("[Link]")
>>> [Link]()
'123 Susan 12.5 8.1 7.6 3.2\n
456 Brad 4.0 11.6 6.5 2.7 12\n
789 Jenn 8.0 8.0 8.0 8.0 7.5\n'
File Input Template
• A template for reading files in Python:

name = open("filename")
for line in name:
statements
>>> input = open("[Link]")
>>> for line in input:
... print([Link]()) # strip() removes \n

123 Susan 12.5 8.1 7.6 3.2


456 Brad 4.0 11.6 6.5 2.7 12
789 Jenn 8.0 8.0 8.0 8.0 7.5
Exercise
• Write a function input_stats that accepts a file name as
a parameter and that reports the longest line in the file.
• example input file, [Link]:
Beware the Jabberwock, my son,
the jaws that bite, the claws that catch,
Beware the JubJub bird and shun
the frumious bandersnatch.

• expected output:
>>> input_stats("[Link]")
longest line = 42 characters
the jaws that bite, the claws that catch,

[Link]
Exercise Solution
def input_stats(filename):
input = open(filename)
longest = ""
for line in input:
if len(line) > len(longest):
longest = line

print("Longest line =", len(longest))


print(longest)

input_stats("[Link]")
Writing To A Text File
• Program must also be able to write data to files for other programs
(or humans) to read
• Many text files are created (written to) automatically and as needed
• Automatic creation of web pages
• Database and program log files
Writing To A Text File
• Writing strings to a file
• There are several functions for writing data to a file
• To write a single string to a text file use the write() method
• Example
any_file.write(“This is a test…\n”)
any_file.write(“This is only a test\n” )
• Note both strings could have been concatenated together into one string and
have the same result using one write statement
Writing To A Text File
• Writing a list of strings to a file
• The writelines() method is the complement function to readlines()
• It takes a list of strings and prints them to a file
• Example
any_file.writelines( any_list )
• The newline characters must be embedded in each string for proper formatting
(as needed)
Writing Files
name = open("filename", "w")
name = open("filename", "a")
• opens file for write (deletes previous contents), or
• opens file for append (new data goes after previous data)

[Link](str) - writes the given string to the file


[Link]() - saves file once writing is done

>>> out = open("[Link]", "w")


>>> [Link]("Hello, world!\n")
>>> [Link]("How are you?")
>>> [Link]()
>>> open("[Link]").read()
'Hello, world!\nHow are you?'
Tokenizing File Input
• Use split to tokenize line contents when reading files.
• You may want to type-cast tokens: type(value)

>>> f = open("[Link]")
>>> line = [Link]()
>>> line
'hello world 42 3.14\n'

>>> tokens = [Link]()


>>> tokens
['hello', 'world', '42', '3.14']

>>> word = tokens[0]


'hello'
>>> answer = int(tokens[2])
42
>>> pi = float(tokens[3])
3.14
Basic cryptography
• Rotation cipher - shift each letter by some fixed amount
• Caesar cipher - shift each letter forward by 3
"the cake is a lie" becomes
"wkh fdnh lv d olh"

• Substitution cipher - transform each letter into another


• not a linear shift; uses some kind of letter mapping
• similar to "cryptogram" or "cryptoquip" games in newspaper
Questions?

You might also like