Functions Files Notes Python
Functions Files Notes Python
Chapter 5: Functions
A function is a group of statements that exist within a program for the purpose of performing a specific
task. Instead of writing a large program as one long sequence of statements, it can be written as several small
functions, each one performing a specific part of the task.
These small functions can then be executed in the desired order to perform the overall task. This
approach is sometimes called divide and conquer because a large task is divided into several smaller tasks that
are easily performed.
Python gives you many built-in functions like print(), etc. but you can also create your own functions. These
functions are called user-defined functions.
Defining a Function :
You can define functions to provide the required functionality. Here are simple rules to define a function in
Python.
● Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
● Any input parameters or arguments should be placed within these parentheses. You can also define
parameters inside these parentheses.
● The code block within every function starts with a colon (:) and is indented.
● The statement return [expression] exits a function, optionally passing back an expression to the caller.
A return statement with no arguments is the same as return None.
Syntax:To create a function you write its definition. Here is the general format of a function definition in
Python:
def function name():
statement
statement
etc.
Beginning at the next line is a set of statements known as a block. A block is simply a set of statements
that belong together as a group. These statements are performed any time the function is executed.
Ex:
def message():
print('I am Arthur,')
print('King of the Britons.')
Calling a Function:
A function definition specifies what a function does, but it does not cause the function to execute. To
execute a function, you must call it. This is how we would call the message function:
message()
When a function is called, the interpreter jumps to that function and executes the statements in its block.
Indentation in Python::
In Python, each line in a block must be indented. As shown in Figure 5-7, the last indented line after a
function header is the last line in the function’s block
Designing a Program to Use Functions:
The Programmers commonly use a technique known as top-down design to break down an algorithm
into functions. In a Flowcharting a Program with Functions: In flowcharts as a tool for designing programs.
In a flowchart, a function call is shown with a rectangle that has vertical bars at each side, as shown in
Figure. The name of the function that is being called is written on the symbol. The example shown in Figure
shows how we would represent a call to the message function.
Local Variables:
A local variable is created inside a function and cannot be accessed by statements that are outside the
function. Different functions can have local variables with the same names because the functions cannot see
each other’s local variables.
(The term local is meant to indicate that the variable can be used only locally, within the function in which it is
created.)
The main function calls the get_name function in line 3. Then, the statement in line 4 tries to access the name
variable. This results in an error because the name variable is local to the get_name function, and statements in
the main function cannot access it.
When this program runs, the main function is called in line 15. Inside the main function, line 5 creates a
local variable named value, assigned the value 5. Then the following state- ment in line 6 calls the show_double
function:
show_double(value)
Notice that value appears inside the parentheses. This means that value is being passed as an argument
to the show_double function, as shown in Figure 5-13 When this state- ment executes, the show_double
function will be called, and the number parameter will be assigned the same value as the value variable. This is
shown in Figure .
Global Variables:
A global variable is accessible to all the functions in a program file.
● Most programmers agree that you should restrict the use of global variables, or not use them at all. The
reasons are as follows:
● Global variables make debugging difficult. Any statement in a program file can change the value of a global
variable. If you find that the wrong value is being stored in a global variable, you have to track down every
statement that accesses it to determine where the bad value is coming from. In a program with thousands of
lines of code, this can be difficult.
● Functions that use global variables are usually dependent on those variables. If you want to use such a
function in a different program, most likely you will have to redesign it so it does not rely on the global
variable.
● Global variables make a program hard to understand. A global variable can be modified by any statement in
the program. If you are to understand any part of the program that uses a global variable, you have to be
aware of all the other parts of the program that access the global variable.
Global Constants:
A global constant is a global name that references a value that cannot be changed. Because a global
constant’s value cannot be changed during the program’s execution,
The Python language does not allow you to create true global constants, you can simulate them with
global variables. If you do not declare a global variable with the global key word inside a function, then you
cannot change the variable’s assignment inside that function.
Value-Returning Functions:
A value-returning function is a function that returns a value back to the part of the program that called it.
Python, as well as most other programming languages, provides a library of prewritten functions that perform
commonly needed tasks. These libraries typically contain a function that generates random numbers.
A value-returning function is a special type of function. It is like a void function in the following ways.
• It is a group of statements that perform a specific task.
• When you want to execute the function, you call it.
The value that is returned from a function can be used like any other value: it can be assigned to a variable,
displayed on the screen, used in a mathematical expression (if it is a number), and so on.
For example, the following statement, which calculates the area of a circle, uses pi. (Notice that we use dot
notation to refer to the variable.)
area = math.pi * radius**2
The math module in the Python standard library contains several functions that are useful for
performing mathematical operations. Table 5-2 lists many of the functions in the math module. These functions
typically accept one or more values as arguments, perform a mathematical operation using the arguments, and
return the result.
# This program demonstrates the sqrt function.
import math
def main():
# Get a number.
number = float(input('Enter a number: '))
output is:
Enter a number: 25
The square root of 25.0 is 5.0
1
choice(seq) :A random item from a list, tuple, or string.
2
randrange ([start,] stop [,step]) : A randomly selected element from range(start, stop, step)
3
random() :A random float r, such that 0 is less than or equal to r and r is less than 1
4
seed([x]) :Sets the integer starting value used in generating random numbers. Call this function
before calling any other random module function. Returns None.
randrange():
Description :The method randrange() returns a randomly selected element from range(start, stop, step).
Syntax: randrange ([start,] stop [,step])
Parameters are
start − Start point of the range. This would be included in the range.
stop − Stop point of the range. This would be excluded from the range.
step − Steps to be added in a number to decide a random number.
Note − This function is not accessible directly, so we need to import random
module and then we need to call this function using random static object.
randint() function:
The following statement shows an example of how you might call the randint function.
number = random.randint (1, 100)
The part of the statement that reads random.randint(1, 100) is a call to the randint function.
Example:1
Program 5-16 shows a complete program that uses the randint function. The statement in line 2 generates a
random number in the range of 1 through 10 and assigns it to the number variable
Notice that both of these files contain function definitions, but they do not contain code that calls the
functions. That will be done by the program or programs that import these modules.
Before continuing, we should mention the following things about module names:
• A module’s file name should end in .py. If the module’s file name does not end in .py you will not be able to
import it into other programs.
• A module’s name cannot be the same as a Python key word. An error would occur, for example, if you named
a module for.
The import Statement
Any Python source file as a module by executing an import statement in some other Python source file.
The import has the following syntax −
import module1[, module2[,... moduleN]
When the interpreter encounters an import statement, it imports the module if the module is present in
the search path. A search path is a list of directories that the interpreter searches before importing a module.
For example, to import the module support.py, you need to put the following command at the top of the script.
# Import module support
import support
1.Introduction to File:
When a program needs to save data for later use, it writes the data in a file. The data can be read from
the file at a later time. The programs you have written so far require the user to reenter data each time the
program runs, because data that is stored in RAM (referenced by variables) disappears once the program stops
running.
If a program is to retain data between the times it runs, it must have a way of saving it. Data is saved in a
file, which is usually stored on a computer’s disk. Once the data is saved in a file, it will remain there after the
program stops running. Data that is stored in a file can be retrieved and used at a later time.
Most of the commercial software packages that you use on a day-to-day basis store data in files.
The following are a few examples.
• Word processors. Word processing programs are used to write letters, memos, reports, and other documents.
The documents are then saved in files so they can be edited and printed.
• Image editors. Image editing programs are used to draw graphics and edit images such as the ones that you
take with a digital camera. The images that you create or edit with an image editor are saved in files.
• Spreadsheets. Spreadsheet programs are used to work with numerical data. Numbers and mathematical
formulas can be inserted into the rows and columns of the spreadsheet. The spreadsheet can then be saved in a
file for use later.
• Games. Many computer games keep data stored in files.
• Web browers. Sometimes when you visit a Web page, the browser stores a small file known as a cookie on
your computer. Cookies typically contain information about the browsing session, such as the contents of a
shopping cart.
ii). Process the file—In this step data is either written to the file
(if it is an output file) or read from the file (if it is an input file).
For example, look at the code in Program 6-8. This program gets sales amounts for a series of days from
the user and writes those amounts to a file named sales.txt. The user specifies the number of days of sales data
he or she needs to enter. In the sample run of the program, the user enters sales amounts for five days.
4. Processing Records
The data that is stored in a file is frequently organized in records. A record is a complete set of data
about an item, and a field is an individual piece of data within a record.
When data is written to a file, it is often organized into records and fields. A record is a complete set of
data that describes one item, and a field is a single piece of data within a record. For example, suppose we want
to store data about employees in a file. The file will contain a record for each employee. Each record will be a
collection of fields, such as name, ID number, and department. This is illustrated in Figure 6-18.
Each time you write a record to a sequential access file, you write the fields that make up the record, one
after the other. For example, Figure 6-19 shows a file that contains three employee records. Each record consists
of the employee’s name, ID number, and department.
Chapter-7:Lists and Tuples
I. Sequences:
A sequence is an object that holds multiple items of data, stored one after the other. You can perform
operations on a sequence to examine and manipulate the items stored in it.
The indexes of the elements in this list are 0, 1, 2, and 3. We can print the elements of the list with the following
statement:
print(my_list[0], my_list[1], my_list[2], my_list[3])
The index 21 identifies the last element in a list, 22 identifies the next to last element, and so forth. The
following code shows an example:
my_list = [10, 20, 30, 40]
print(my_list[−1], my_list[−2], my_list[−3], my_list[−4])
In this example, the print function will display:
40 30 20 10
The first statement assigns the list [10, 20, 30, 40] to the my_list variable. The second statement calls the len
function, passing the my_list variable as an argument.
The function returns the value 4, which is the number of elements in the list. This value is assigned to the size
variable.
The len function can be used to prevent an IndexError exception when iterating over a list with a loop. Here is
an example:
The statement in line 3 assigns 99 to numbers[0]. This changes the first value in the list to 99. When the
statement in line 4 executes, it will display [99, 2, 3, 4, 5]
Concatenating Lists
To concatenate means to join two things together. You can use the + operator to concatenate two lists. Here
is an example:
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
list3 = list1 + list2
After this code executes, list1 and list2 remain unchanged, and list3 references the following list:
[1, 2, 3, 4, 5, 6, 7, 8]
The following interactive mode session also demonstrates list concatenation:
>>> girl_names = ['Joanne', 'Karen', 'Lori']
>>> boy_names = ['Chris', 'Jerry', 'Will']
>>> all_names = girl_names + boy_names
>>> print(all_names)
['Joanne', 'Karen', 'Lori', 'Chris', 'Jerry', 'Will']
The following statement uses a slicing expression to get the elements from indexes 2 up to, but not including, 5:
mid_days = days[2:5]
After this statement executes, the mid_days variable references the following list:
['Tuesday', 'Wednesday', 'Thursday']
The following interactive mode session shows an example:
1 >>> numbers = [1, 2, 3, 4, 5]
2 >>> print(numbers)
3 [1, 2, 3, 4, 5]
4 >>> print(numbers[:3])
5 [1, 2, 3]
6 >>>
Notice that line 4 sends the slice numbers[:3] as an argument to the print function. Because the starting index
was omitted, the slice contains the elements from index 0 up to 3.
Python uses the length of the list as the end index. The following interactive mode session shows an example:
1 >>> numbers = [1, 2, 3, 4, 5] e
2 >>> print(numbers) e
3 [1, 2, 3, 4, 5]
4 >>> print(numbers[2:]) e
5 [3, 4, 5]
6 >>>
Notice that line 4 sends the slice numbers[2:] as an argument to the print function. Because the ending index
was omitted, the slice contains the elements from index 2 through the end of the list.
The following interactive mode session shows an example of a slicing expression with a step value:
1 >>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2 >>> print(numbers)
3 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
4 >>> print(numbers[1:8:2])
5 [2, 4, 6, 8]
6 >>>
In the slicing expression in line 4, the third number inside the brackets is the step value. A step value of 2, as
used in this example, causes the slice to contain every second element from the specified range in the list.
Python adds a negative index to the length of a list to get the position referenced by that index. The following
interactive mode session shows an example:
1 >>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2 >>> print(numbers)
3 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
4 >>> print(numbers[-5:])
5 [6, 7, 8, 9, 10]
6 >>>
You can use the not in operator to determine whether an item is not in a list. Here is an example:
if search not in prod_nums:
print(search, 'was not found in the list.')
else:
print(search, 'was found in the list.')
The max function accepts a sequence, such as a list, as an argument and returns the item that has the highest
value in the sequence.
Here is an example:
my_list = [5, 4, 3, 2, 50, 40, 30]
print('The highest value is', max(my_list))
This code will display the following:
The highest value is 50
Two-Dimensional Lists
A two-dimensional list is a list that has other lists as its elements. The elements of a list can be virtually
anything, including other lists. To demonstrate, look at the following interactive session:
1 >>> students = [['Joe', 'Kim'], ['Sam', 'Sue'], ['Kelly', 'Chris']]
2 >>> print(students)
3 [['Joe', 'Kim'], ['Sam', 'Sue'], ['Kelly', 'Chris']]
4 >>> print(students[0])
5 ['Joe', 'Kim']
6 >>> print(students[1]) e 7 ['Sam', 'Sue']
8 >>> print(students[2])
9 ['Kelly', 'Chris']
10 >>>
Lists of lists are also known as nested lists, or two-dimensional lists. It is common to think of a two-dimensional
list as having rows and columns of elements
==xxx==