Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Module 1

The document discusses functions, parameters, return values, scope, and exception handling in Python. It provides examples of defining functions, using parameters, returning values, and differences between local and global scopes. It also demonstrates try/except blocks for exception handling.

Uploaded by

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

Module 1

The document discusses functions, parameters, return values, scope, and exception handling in Python. It provides examples of defining functions, using parameters, returning values, and differences between local and global scopes. It also demonstrates try/except blocks for exception handling.

Uploaded by

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

Module 1.

Functions: def Statements with Parameters, Return Values and return Statements, The None
Value, Keyword Arguments and print(), Local and Global Scope, The global Statement,
Exception Handling, A Short Program: Guess the Number

Functions:
Function is like a mini-program within a program. A major purpose of functions is to group code
that gets executed multiple times.

 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:
def Statements with Parameters

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. The value stored in a parameter is forgotten when the function returns. For example, if
you added print(name) after hello('Bob') in the previous program, the program would give you a
NameError because there is no variable named name. This variable was destroyed after the
function call hello('Bob') had returned, so print(name) would refer to a name variable that does
not exist.

Return Values and return Statements

The value that a function call evaluates to is called the return value of the function. 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:
 The return keyword
 The value or expression that the function should return
 When this program starts, 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.
 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.
 But since all function calls need to evaluate to a return value, print() returns None.
 Python adds return None to the end of any function definition with no return statement
 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()

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.
end
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.

The output is printed on a single line because there is no longer a newline printed after 'Hello'.
Instead, the blank string is printed. This is useful if you need to disable the newline that gets
added to the end of every print() function call.
sep
When you pass multiple string values to print(), the function will automatically separate them
with a single space.

Local and Global Scope

 Parameters and variables that are assigned in a called function are said to exist in that
function’s local scope.
 Variables that are assigned outside all functions are said to exist in the global scope.
 A variable that exists in a local scope is called a local variable, 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.
Otherwise, the next time you ran your program, the variables would remember their
values from the last time you ran it.
 A local scope is created whenever a function is called. Any variables assigned in this
function exist within the local scope. When the function returns, the local scope is
destroyed, and these variables are forgotten. The next time you call this function, the
local variables will not remember the values stored in them from the last time the
function was called.

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.

1. Local Variables Cannot Be Used in the Global Scope

Consider this program, which will cause an error when you run it:

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. 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.
2. Local Scopes Cannot Use Variables in Other Local Scopes

 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, and 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, 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.

3. Global Variables Can Be Read from a Local Scope

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.
4. 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. But technically, it’s perfectly legal to do so in Python.

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.”
Exception Handling

Right now, 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-byzero” error. Open a new
file editor window and enter the following code, saving it as zeroDivide.py:
A Short Program: Guess the Number (Refer Text Book)

You might also like