0% found this document useful (0 votes)
4 views

Module 2 Function- List

Chapter 3 covers functions in Python, explaining how to declare and call functions, use parameters, return values, and the concept of None. It also discusses local and global scope, the importance of variable naming, and how to handle exceptions. Additionally, it introduces lists as a data type that holds multiple values in an ordered sequence.

Uploaded by

vivekgowda2006
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Module 2 Function- List

Chapter 3 covers functions in Python, explaining how to declare and call functions, use parameters, return values, and the concept of None. It also discusses local and global scope, the importance of variable naming, and how to handle exceptions. Additionally, it introduces lists as a data type that holds multiple values in an ordered sequence.

Uploaded by

vivekgowda2006
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Chapter -3

FUNCTIONS
A function is like a mini-program within a program.

The print(), input(), and len() functions several built in functions like these, but you can also
write your own functions.

# function declaration
def hello():
print('Howdy!')
print('Howdy!!!')
print('Hello there.')
# Function Calling
hello()
hello()
hello()

 The first line is a def statement, which defines a function named hello().
 The code in the block that follows the def statement is the body of the function.
 This code is executed when the function is called, not when the function is first
defined
 The hello() lines after the function are function calls.
 In code, a function call is just the function’s name followed by parentheses, possibly with
some number of arguments in between the parentheses.
 When the program execution reaches these calls, it will jump to the top line in the function
and begin executing the code there.
 When it reaches the end of the function, the execution returns to the line that called the
function and continues moving through the code as before

Since this program calls hello() three times, the code in the hello() function is executed three
times. When you run this program, the output looks like this:
Howdy!
Howdy!!!
Hello there.
Howdy!
Howdy!!!
Hello there.
Howdy!
Howdy!!!
Hello there.
def Statements with Parameters

When you call the print() or len() function, you pass in values, called arguments in this
context, by typing them between the parentheses.

You can also define your own functions that accept arguments. Type this example into the
file editor and save it as helloFunc2.py

 The definition of the hello() function in this program has a parameter called name .
 A parameter is a variable that an argument is stored in when a function is called.
 The first time the hello () function is called, it’s with the argument 'Alice' .
 The program execution enters the function, and the variable name is automatically set
to 'Alice', which is what gets printed by the print ( ) statement.
 One special thing to note about parameters is that the value stored in a parameter is
forgotten when the function returns. This is similar to how a program’s variables are
forgotten when the program terminates.

Return Values and return Statements


 When creating a function using the def statement, you can specify what the return
value should be with a return statement.
 A return statement consists of the following:
o The return keyword
o The value or expression that the function should return
The following program defines a function that returns a different string depending on what
number it is passed as an argument.

 Python first imports the random module

 Then the getAnswer() function is defined . Because the function is being defined (and
not called), the execution skips over the code in it. Next, the random.randint()
function is called with two arguments, 1 and 9

 It evaluates to a random integer between 1 and 9 (including 1 and 9 themselves), and


this value is stored in a variable named r

 The getAnswer() function is called with r as the argument .

 The program execution moves to the top of the getAnswer() function , and the value
r is stored in a parameter named answerNumber.

 Then, depending on this value in answerNumber, the function returns one of many
possible string values.

 The program execution returns to the line at the bottom of the program that originally
called getAnswer() .

 The returned string is assigned to a variable named fortune, which then gets passed to
a print () call and is printed to the screen.
The None Value

 In Python there is a value called None, which represents the absence of a value.

 None is the only value of the NoneType data type. (Other programming languages
might call this value null, nil, or undefined.)

 Just like the Boolean True and False values, None must be typed with a capital N.

 This value-without-a-value can be helpful when you need to store something that
won’t be confused for a real value in a variable.

 One place where None is used is as the return value of print(). The print() function
displays text on the screen, but it doesn’t need to return anything in the same way
len() or input() does.

Example Program

>>> spam = print('Hello!')


Hello!
>>> None == spam
True

Python adds return None to the end of any function definition with no return
statement.

This is similar to how a while or for loop implicitly ends with a continue statement.
Also, if you use a return statement without a value (that is, just the return keyword by
itself), then None is returned

Keyword Arguments and print()


Most arguments are identified by their position in the function call. For example,
random.randint(1, 10) is different from random.randint(10, 1).

The function call random.randint(1, 10) will return a random integer between 1 and 10,
because the first argument is the low end of the range and the second argument is the high
end (while random.randint(10, 1) causes an error).

However, keyword arguments are identified by the keyword put before them in the function
call. Keyword arguments are often used for optional parameters.

For example, the print() function has the optional parameters end and sep to specify what
should be printed at the end of its arguments and between its arguments (separating them),
respectively.
print('Hello')
print('World')

the output would look like this:

Hello
World

The two strings appear on separate lines because the print() function automatically adds a
newline character to the end of the string it is passed.

However, you can set the end keyword argument to change this to a different string. For
example, if the program were this:

print('Hello', end='')
print('World')

the output would look like this:

HelloWorld

when you pass multiple string values to print (), the function will automatically separate them
with a single space.

>>> print('cats', 'dogs', 'mice')


cats dogs mice

you could replace the default separating string by passing the sep keyword argument.

>>> print('cats', 'dogs', 'mice', sep=',')


cats, dogs, mice

Local and Global Scope

 Parameters and variables that are assigned in a called function are said to exist in that
function’s local scope., A variable that exists in a local scope is called a local
variable

 Variables that are assigned outside all functions are said to exist in the global scope.
while a variable that exists in the global scope is called a global variable.

 A variable must be one or the other; it cannot be both local and global.

 Think of a scope as a container for variables. When a scope is destroyed, all the
values stored in the scope’s variables are forgotten.

 There is only one global scope, and it is created when your program begins. When
your program terminates, the global scope is destroyed, and all its variables are
forgotten.
Scopes matter for several reasons:

• Code in the global scope cannot use any local variables.

• However, a local scope can access global variables.

• Code in a function’s local scope cannot use variables in any other local scope.

• You can use the same name for different variables if they are in different scopes.
That is, there can be a local variable named spam and a global variable also named
spam

The reason Python has different scopes instead of just making everything a global
variable is so that when variables are modified by the code in a particular call to a
function, the function interacts with the rest of the program only through its
parameters and the return value.

This narrows down the list code lines that may be causing a bug. If your program
contained nothing but global variables and had a bug because of a variable being set
to a bad value, then it would be hard to track down where this bad value was set.

It could have been set from anywhere in the program—and your program could be
hundreds or thousands of lines long! But if the bug is because of a local variable with
a bad value, you know that only the code in that one function could have set it
incorrectly.

While using global variables in small programs is fine, it is a bad habit to rely on
global variables as your programs get larger and larger.

Local Variables Cannot Be Used in the Global Scope

def spam():
eggs = 31337

spam()
print(eggs)
 The error happens because the eggs variable exists only in the local scope created
when spam() is called.
 Once the program execution returns from spam, that local scope is destroyed, and
there is no longer a variable named eggs.
 So when your program tries to run print(eggs), Python gives you an error saying that
eggs is not defined.
 This makes sense if you think about it; when the program execution is in the global
scope, no local scopes exist, so there can’t be any local variables. This is why only
global variables can be used in the global scope.

Local Scopes Cannot Use Variables in Other Local Scopes

A new local scope is created whenever a function is called, including when a function is
called from another function. Consider this program:

def spam():
eggs = 99
bacon()
print(eggs)

def bacon():
ham = 101
eggs = 0

spam()

When the program starts, the spam () function is called , and a local scope is created. The
local variable eggs u is set to 99.

Then the bacon () function is called , and a second local scope is created. Multiple local
scopes can exist at the same time. In this new local scope, the local variable ham is set to 101,

a local variable eggs—which is different from the one in spam ()’s local scope—is also
created and set to 0. When bacon () returns, the local scope for that call is destroyed.

The program execution continues in the spam () function to print the value of eggs w, and
since the local scope for the call to spam () still exists here, the eggs variable is set to 99. This
is what the program prints.

The upshot is that local variables in one function are completely separate from the local
variables in another function.
Global Variables Can Be Read from a Local Scope

Consider the following program:

def spam():
print(eggs)

eggs = 42
spam()
print(eggs)

Since there is no parameter named eggs or any code that assigns eggs a value in the spam()
function, when eggs is used in spam(), Python considers it a reference to the global variable
eggs.

This is why 42 is printed when the previous program is run.

Local and Global Variables with the Same Name

 To simplify your life, avoid using local variables that have the same name as a global
variable or another local variable.
 it’s perfectly legal to do so in Python. To see what happens, type the following code
into the file editor and save it as sameName.py:
There are actually three different variables in this program, but confus ingly they are
all named eggs. The variables are as follows:

1. A variable named eggs that exists in a local scope when spam() is called.
2. A variable named eggs that exists in a local scope when bacon() is called.
3. A variable named eggs that exists in the global scope

Since these three separate variables all have the same name, it can be confusing to
keep track of which one is being used at any given time. This is why you should avoid
using the same variable name in different scopes.

The global Statement


If you need to modify a global variable from within a function, use the global
statement. If you have a line such as global eggs at the top of a function, it tells
Python,

“In this function, eggs refers to the global variable, so don’t create a local variable
with this name.” For example, type the following code into the file editor and save it
as sameName2.py:

Because eggs is declared global at the top of spam(), when eggs is set to 'spam', this
assignment is done to the globally scoped spam. No local spam variable is created.

There are four rules to tell whether a variable is in a local scope or global scope:

1. If a variable is being used in the global scope (that is, outside of all functions), then
it is always a global variable.
2. If there is a global statement for that variable in a function, it is a global variable.
3. Otherwise, if the variable is used in an assignment statement in the function, it is a
local variable.
4. But if the variable is not used in an assignment statement, it is a global variable.
def spam():
global eggs
eggs = 'spam' # this is the global

def bacon():
eggs = 'bacon' # this is a local

def ham():
print(eggs) # this is the global

eggs = 42 # this is the global


spam()
print(eggs)

 In the spam() function, eggs is the global eggs variable, because there’s a global
statement for eggs at the beginning of the function

 In bacon(), eggs is a local variable, because there’s an assignment statement for it in


that function .

 In ham(), eggs is the global variable, because there is no assignment statement or


global statement for it in that function

Exception Handling
getting an error, or exception, in your Python program means the entire program will crash.
You don’t want this to happen in real-world programs. Instead, you want the program to
detect errors, handle them, and then continue to run.
For example, consider the following program, which has a “divide-by-zero” error.
 A ZeroDivisionError happens whenever you try to divide a number by zero.

 From the line number given in the error message, you know that the return statement
in spam() is causing an error.

 Errors can be handled with try and except statements. The code that could potentially
have an error is put in a try clause.

 The program execu tion moves to the start of a following except clause if an error
happens. You can put the previous divide-by-zero code in a try clause and have an
except clause contain code to handle what happens when this error occurs.
A Short Program: Guess the Number

A simple “guess the number” game. When you run this program, the output will look
something like this:

I am thinking of a number between 1 and 20.


Take a guess.
10
Your guess is too low.
Take a guess.
15
Your guess is too low.
Take a guess.
17
Your guess is too high.
Take a guess.
16
Good job! You guessed my number in 4 guesses!

guessTheNumber.py:
 The program imports the random module so that it can use the random.randint()
function to generate a number for the user to guess.

 The return value, a random integer between 1 and 20, is stored in the variable
secretNumber.

 The first thing that happens in the loop is that the player types in a guess.

 Since input() returns a string, its return value is passed straight into int(), which
translates the string into an integer value. This gets stored in a variable named guess.

 These few lines of code check to see whether the guess is less than or greater than the
secret number. In either case, a hint is printed to the screen

 If the guess is neither higher nor lower than the secret number, then it must be equal
to the secret number, in which case you want the program execution to break out of
the for loop

 After the for loop, the previous if...else statement checks whether the player has
correctly guessed the number and prints an appropriate message to the screen.

 In both cases, the program displays a variable that contains an integer value
(guessesTaken and secretNumber).

 Since it must concatenate these integer values to strings, it passes these variables to
the str() function, which returns the string value form of these integers.

 Now these strings can be concatenated with the + operators before finally being
passed to the print() function call
Module 2 Python

CHAPTER 2: LISTS

1. The List Data Type


2. Working with Lists
3. Augmented Assignment Operators
4. Methods
5. Example Program: Magic 8 Ball with a List
6. List-like Types: Strings and Tuples
7. References

1.1 The List Data Type


➢ A list is a value that contains multiple values in an ordered sequence.
➢ A list value looks like this: ['cat', 'bat', 'rat', 'elephant'].
➢ A list begins with an opening square bracket and ends with a closing square bracket, [].
➢ Values inside the list are also called items and are separated with commas.The spam variable ❶ is still
assigned only one value: the list value(contains multiple values).

➢ The value [] is an empty list that contains no values, similar to '', the empty string.

Getting Individual Values in a List with Indexes


➢ Say you have the list ['cat', 'bat', 'rat', 'elephant'] stored in a variable named spam.
➢ The Python code spam[0] would evaluate to 'cat', and spam[1] would evaluate to 'bat', and so on.

➢ The first value in the list is at index 0, the second value is at index 1, and the third value is at index
2, and so on.
➢ For example, type the following expressions into the interactive shell.
Module 2 Python

➢ The expression 'Hello ' + spam[0] evaluates to 'Hello ' + 'cat' because spam[0] evaluates to the
string 'cat'. This expression in turn evaluates to the string value 'Hello cat'.
➢ If we use an index that exceeds the number of values in the list value then, python gives IndexError.

➢ Indexes can be only integer values, not floats. The following example will cause a TypeError error:

➢ Lists can also contain other list values. The values in these lists of lists ca be accessed using
multiple indexes.

➢ The first index dictates which list value to use, and the second indicates the value within the list
value. Ex, spam[0][1] prints 'bat', the second value in the first list.

Negative Indexes

➢ We can also use negative integers for the index. The integer value -1 refers to the last index in a list,
the value -2 refers to the second-to-last index in a list, and so on.
Module 2 Python

Getting Sublists with Slices

➢ An index will get a single value from a list, a slice can get several values from a list, in the form of a
new list.
➢ A slice is typed between square brackets, like an index, but it has two integers separated by a colon.
➢ Difference between indexes and slices.
o spam[2] is a list with an index (one integer).
o spam[1:4] is a list with a slice (two integers).
➢ In a slice, the first integer is the index where the slice starts. The second integer is the index where
the slice ends (but will not include the value at the second index).

➢ As a shortcut, we can leave out one or both of the indexes on either side of the colon in the slice.
o Leaving out the second index is the same as using the length of the list, which will slice to
the end of the list.

Getting a List’s Length with len()

➢ The len() function will return the number of values that are in a list value.

Changing Values in a List with Indexes

➢ We can also use an index of a list to change the value at that index. Ex: spam[1] = 'aardvark' means
“Assign the value at index 1 in the list spam to the string 'aardvark'.”
Module 2 Python

List Concatenation and List Replication

➢ The + operator can combine two lists to create a new list value in the same way it combines two
strings into a new string value.
➢ The * operator can also be used with a list and an integer value to replicate the list.

Removing Values from Lists with del Statemnts


➢ The del statement will delete values at an index in a list.

➢ The del statement can also be used to delete a variable After deleting if we try to use the variable,
we will get a NameError error because the variable no longer exists.
➢ In practice, you almost never need to delete simple variables.
➢ The del statement is mostly used to delete values from lists.

1.2 Working with Lists


➢ When we first begin writing programs, it’s tempting to create many individual variables to store a group
of similar values.
Module 2 Python

➢ Which is bad way to write code because it leads to have a duplicate code in the program.

➢ Instead of using multiple, repetitive variables, we can use a single variable that contains a list value.
➢ For Ex: The following program uses a single list and it can store any number of cats that the user types

in.
➢ Program:
➢ Output:

➢ The benefit of using a list is that our data is now in a structure, so our program is much more flexible in
processing the data than it would be with several repetitive variables.
Module 2 Python

Using for Loops with Lists

➢ A for loop repeats the code block once for each value in a list or list-like value.
Program

Output:

➢ A common Python technique is to use range (len(someList)) with a for loop to iterate over the

indexes of a list.

➢ The code in the loop will access the index (as the variable i), the value at that index (as supplies[i])
and range(len(supplies)) will iterate through all the indexes of supplies, no matter how many items
it contains.

The in and not in Operators

➢ We can determine whether a value is or isn’t in a list with the in and not in operators.
➢ in and not in are used in expressions and connect two values: a value to look for in a list and the list
where it may be found and these expressions will evaluate to a Boolean value.

➢ The following program lets the user type in a pet name and then checks to see whether the name is
in a list of pets.
Program
Module 2 Python

Output

The Multiple Assignment Trick

➢ The multiple assignment trick is a shortcut that lets you assign multiple variables with the values in
a list in one line of code.

➢ Instead of left-side program we could type the right-side program to assignment multiple variables
but the number of variables and the length of the list must be exactly equal, or Python will give you
a ValueError:

Augmented Assignment Operators

➢ When assigning a value to a variable, we will frequently use the variable itself.

➢ Instead of left-side program we could use right-side program i.e., with the augmented assignment
operator += to do the same thing as a shortcut.
➢ The Augmented Assignment Operators are listed in the below table:

➢ The += operator can also do string and list concatenation, and the *= operator can do string and list
replication.
Module 2 Python

1.3 Methods

➢ A method is same as a function, except it is “called on” a value.


➢ The method part comes after the value, separated by a period.
➢ Each data type has its own set of methods.
➢ The list data type has several useful methods for finding, adding, removing, and manipulating values
in a list.
Finding a Value in a List with the index() Method

➢ List values have an index() method that can be passed a value, and if that value exists in the list, the
index of the value is returned. If the value isn’t in the list, then Python produces a ValueError error.

➢ When there are duplicates of the value in the list, the index of its first appearance is returned.

Adding Values to Lists with the append() and insert() Methods

➢ To add new values to a list, use the append() and insert() methods.
➢ The append() method call adds the argument to the end of the list.

➢ The insert() method can insert a value at any index in the list. The first argument to insert() is the
index for the new value, and the second argument is the new value to be inserted.
Module 2 Python

➢ Methods belong to a single data type.


➢ The append() and insert() methods are list methods and can be called only on list values, not on
other values such as strings or integers.

Removing Values from Lists with remove()

➢ The remove() method is passed the value to be removed from the list it is called on.

➢ Attempting to delete a value that does not exist in the list will result in a ValueError error.

➢ If the value appears multiple times in the list, only the first instance of the value will be removed.

➢ The del statement is good to use when you know the index of the value you want to remove from
the list. The remove() method is good when you know the value you want to remove from the list.
Module 2 Python

Sorting the Values in a List with the sort() Method


➢ Lists of number values or lists of strings can be sorted with the sort() method.

➢ You can also pass True for the reverse keyword argument to have sort() sort the values in reverse
order.

➢ There are three things you should note about the sort() method.
o First, the sort() method sorts the list in place; don’t try to return value by writing code like
spam = spam.sort().
o Second, we cannot sort lists that have both number values and string values in them.

o Third, sort() uses “ASCIIbetical order(upper case)” rather than actual alphabetical
order(lower case) for sorting strings.

➢ If we need to sort the values in regular alphabetical order, pass str.lower for the key keyword
argument in the sort() method call.

1.4 Example Program: Magic 8 Ball with a List

➢ We can write a much more elegant version of the Magic 8 Ball program. Instead of several lines of
nearly identical elif statements, we can create a single list.
Module 2 Python

➢ The expression you use as the index into messages: random .randint(0, len(messages) - 1). This
produces a random number to use for the index, regardless of the size of messages. That is, you’ll
get a random number between 0 and the value of len(messages) - 1.

Exceptions to Indentation Rules in Python

➢ The amount of indentation for a line of code tells Python what block it is in.
➢ ists can actually span several lines in the surce code file. The indentation of these lines do not

matter; Python knows that until it sees the ending square bracket, the list is not finished.

➢ We can also split up a single instruction across multiple lines using the \ line continuation character
at the end.

1.5 List-like Types: Strings and Tuples

➢ Lists aren’t the only data types that represent ordered sequences of values.
➢ Ex, we can also do these with strings: indexing; slicing; and using them with for loops, with len(),
and with the in and not in operators.
Module 2 Python

Mutable and Immutable Data Types


String
➢ However, a string is immutable: It cannot be changed. Trying to reassign a single character in a
string results in a TypeError error.

➢ The proper way to “mutate” a string is to use slicing and concatenation to build a new string by
copying from parts of the old string.

➢ We used [0:7] and [8:12] to refer to the characters that we don’t wish to replace. Notice that the
original 'Zophie a cat' string is not modified because strings are immutable.
List
➢ A list value is a mutable data type: It can have values added, removed, or changed.

➢ The list value in eggs isn’t being changed here; rather, an entirely new and different list value ([4, 5,
6]) is overwriting the old list value ([1, 2, 3]).

Figure: When eggs = [4, 5, 6] is executed, the contents of eggs are replaced with a new list value.
➢ If we want to modify the original list in eggs to contain [4, 5, 6], you would have to delete the items
in that and then add items to it.
Module 2 Python

Figure: The del statement and the append() method modify the same list value in place.

The Tuple Data Type


➢ The tuple data type is almost identical to the list data type, except in two ways.
➢ irst, tuples are typed with parentheses, ( and ), instead of square brackets, [ and ].

➢ Second, benefit of using tuples instead of lists is that, because they are immutable and their contents
don’t change. Tuples cannot have their values modified, appended, or removed.

➢ If you have only one value in your tuple, you can indicate this by placing a trailing comma after the
value inside the parentheses.

Converting Types with the list() and tuple() Functions


➢ The functions list() and tuple() will return list and tuple versions of the values passed to them.
Module 2 Python

➢ Converting a tuple to a list is handy if you need a mutable version of a tuple value.
1.6 References
➢ As we’ve seen, variables store strings and integer values.

➢ We assign 42 to the spam variable, and then we copy the value in spam and assign it to the variable
cheese. When we later change the value in spam to 100, this doesn’t affect the value in cheese. This
is because spam and cheese are different variables that store different values.
➢ But lists works differently. When we assign a list to a variable, we are actually assigning a list
reference to the variable. A reference is a value that points to some bit of data, and a list reference is
a value that points to a list.

➢ When we create the list ❶, we assign a reference to it in the spam variable. But the next line copies
only the list reference in spam to cheese, not the list value itself. This means the values stored in
spam and cheese now both refer to the same list.
➢ There is only one underlying list because the list itself was never actually copied. So when we
modify the first element of cheese, we are modifying the same list that spam refers to.
➢ List variables don’t actually contain lists—they contain references to lists.

Figure: spam = [0, 1, 2, 3, 4, 5] stores a reference to a list, not the actual list.
Module 2 Python

➢ The reference in spam is copied to cheese. Only a new reference was created and stored in cheese,
not a new list.

Figure: spam = cheese copies the reference, not the list


➢ When we alter the list that cheese refers to, the list that spam refers to is also changed, because both
cheese and spam refer to the same list.

Figure: cheese[1] = 'Hello!' modifies the list that both variables refer to
➢ Variables will contain references to list values rather than list values themselves.
➢ But for strings and integer values, variables will contain the string or integer value.
➢ Python uses references whenever variables must store values of mutable data types, such as lists or
dictionaries. For values of immutable data types such as strings, integers, or tuples, Python variables
will store the value itself.
Passing References
➢ References are particularly important for understanding how arguments get passed to functions.
➢ When a function is called, the values of the arguments are copied to the parameter variables.

Program Output
➢ when eggs() is called, a return value is not used to assign a new value to spam.
➢ Even though spam and someParameter contain separate references, they both refer to the same list.
This is why the append('Hello') method call inside the function affects the list even after the
function call has returned.

You might also like