Python - Module 2
Python - Module 2
Python - Module 2
• The program execution (or simply, execution) is a term for the current
instruction being executed.
Flow Control Statements
if Statements
• An if statement’s clause (that is, the block following the if statement)
will execute if the statement’s condition is True. The clause is skipped
if the condition is False.
• In Python, an if statement consists of the following:
• The if keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the if
clause)
Flow Control Statements
• All flow control statements end with a colon and are followed by a
new block of code (the clause).
Flow Control Statements
else Statements
• The else clause is executed only when the if statement’s condition is
False
• An else statement doesn’t have a condition, and in code, an else
statement always consists of the following:
• The else keyword
• A colon
• Starting on the next line, an indented block of code (called the else
clause)
Flow Control Statements
if name == 'Alice':
print('Hi, Alice.')
else:
print('Hello, stranger.')
Flow Control Statements
elif Statements
• The elif statement is an “else if” statement that always follows an if or
another elif statement.
• It provides another condition that is checked only if any of the previous
conditions were False.
• In code, an elif statement always consists of the following:
• The elif keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the elif clause)
Flow Control Statements
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
Flow Control Statements
Flow Control Statements
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 100:
print('You are not Alice, grannie.')
e value 3000 before this code is executed. You might expect the code to
elif age > 2000:
print the string 'Unlike you, Alice is not an undead, immortal vampire.'. Ho
wever, because the age > 100 condition is True (after all, 3000 is greater than
100) u, the string 'You are not Alice, grannie.' is printed, and the rest o
print('Unlike you, Alice is not an undead, immortal vampire.')
Say the age variable contains thf the elif statements are automatically skipped
Flow Control Statements
while Loop Statements
• The code in a while clause will be executed as long as the while
statement’s condition is True.
• In code, a while statement always consists of the following:
• The while keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the while clause)
while Loop Statements
• The difference between if and while lies in how they behave.
• At the end of an if clause, the program execution continues after the if
statement.
• But at the end of a while clause, the program execution jumps back to
the start of the while statement.
• The while clause is often called the while loop or just the loop
while Loop Statements
• Python also comes with a set of modules called the standard library.
• Each module is a Python program that contains a related group of
functions that can be embedded in your programs.
• For example, the math module has mathematics related functions, the
random module has random number–related functions, and so on.
• Before you can use the functions in a module, you must import the
module with an import statement.
• In code, an import statement consists of the following:
• The import keyword
• The name of the module
• Optionally, more module names, as long as they are separated by
commas
Importing Modules
Ending a Program Early with sys.exit()
• The program can be terminated, or exit, by calling the sys.exit()
function.
• Since this function is in the sys module, you have to import sys before
your program can use it.
Functions
• A function is like a mini-program within a program.
• 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.
• Since this program calls hello() three times, the code in the hello()
function is executed three times.
Functions
def Statements with Parameters
• When you call the print() or len() function, you pass in values, called
arguments by typing them between the parentheses.
• Own functions can be defined that accept arguments.
• One special thing to note about parameters is that the value stored in
a parameter is forgotten when the function returns
Return Values and return Statements
• When you call the len() function and pass it an argument such as
'Hello', the function call evaluates to the integer value 5, which is the
length of the string you passed it.
• 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
Return Values and return Statements
Return Values and return Statements
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.
• 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.
• >>> spam = print('Hello!')
Hello!
• >>> None == spam
True
Keyword Arguments and print()
• Arguments are identified by their position in the function call.
• 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).
• keyword arguments are identified by the keyword put before them in the function call.
Keyword arguments are often used for optional parameters.
• 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
Keyword Arguments and print()
Keyword Arguments and print()
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 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
Local and Global Scope
• 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.
Local Variables Cannot Be Used in the Global Scope
• def spam():
eggs = 31337
spam()
print(eggs)
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.
Global Variables Can Be Read from a Local Scope
Local and Global Variables with the Same Name
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.”
• 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.
The global Statement
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.