Python - Module 2

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 60

MODULE 2

Control statements and Exception


Handling
Flow control
Flow control statements can decide which Python instructions to
execute under which conditions.
Flow control
• In a flowchart, there is usually more than one way to go from
the start to the end.

• The same is true for lines of code in a computer program.

• Flowcharts represent these branching points with diamonds,


while the other steps are represented with rectangles.

• The starting and ending steps are represented with rounded


Boolean Values
• Boolean data type has only two values: True and False.
Comparison Operators
• Comparison operators compare two values and evaluate down to a
single Boolean value
Comparison Operators
Boolean Operators
• The three Boolean operators (and, or, and not) are used to compare Boolean
values.
• Like comparison operators, they evaluate these expressions down to a
Boolean value
Binary Boolean Operators
• The and & or operators always take two Boolean values (or expressions), so
they’re considered binary operators.
• The and operator evaluates an expression to True if both Boolean values are
True; otherwise, it evaluates to False
>>> True and True
True
>>> True and False
False
Boolean Operators
• The or operator evaluates an expression to True if either of the two Boolean values is True.
• If both are False, it evaluates to False.
>>> False or True
True
>>> False or False
False
The not Operator
• The not operator operates on only one Boolean value (or expression). The not operator
simply evaluates to the opposite Boolean value.
>>> not True
False
>>> not not not not True
True
Mixing Boolean and Comparison Operators
>>> (4 < 5) and (5 < 6)
True
>>> (4 < 5) and (9 < 6)
False
>>> (1 == 2) or (2 == 2)
True
• The computer will evaluate the left expression first, and then it will
evaluate the right expression. When it knows the Boolean value for each,
it will then evaluate the whole expression down to one Boolean value.
Elements of Flow Control
• Flow control statements often start with a part called the condition,
and all are followed by a block of code called the clause
Conditions
• Condition is a more specific name in the context of flow control
statements.
• Conditions always evaluate down to a Boolean value, True or False.
• A flow control statement decides what to do based on whether its
condition is True or False, and almost every flow control statement
uses a condition.
Elements of Flow Control
Blocks of Code
• Lines of Python code can be grouped together in blocks.
• There are three rules for blocks.
1. Blocks begin when the indentation increases.
2. Blocks can contain other blocks.
3. Blocks end when the indentation decreases to zero or to a containing block’s indentation.
Program Execution

• 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

• In the while loop, the condition is


always checked at the start of
each iteration (that is, each time
the loop is executed).
• If the condition is True, then the
clause is executed, and afterward,
the condition is checked again.
• The first time the condition is
found to be False, the while clause
is skipped.
An Annoying while Loop
An Annoying while Loop
break Statements
• If the execution reaches a break statement, it
immediately exits the while loop’s clause.
• In code, a break statement simply contains the
break keyword.
• The first line creates an infinite loop; it is a
while loop whose condition is always True.
• The program execution will always enter the
loop and will exit it only when a break
statement is executed
break Statements
continue Statements
• Continue statements are used inside loops.
• When the program execution reaches a continue statement, the
program execution immediately jumps back to the start of the loop
and reevaluates the loop’s condition.
for Loops and the range() Function
• The while loop keeps looping while its condition is True, but what if you
want to execute a block of code only a certain number of times?
• You can do this with a for loop statement and the range() function.
• In code, a for statement looks something like for i in range(5): and always
includes the following:
• The for keyword
• A variable name
• The in keyword
• A call to the range() method with up to three integers passed to it
• A colon
• Starting on the next line, an indented block of code (called the for clause)
for Loops and the range() Function

• print('My name is')


• for i in range(5):
• print('Jimmy Five Times (' + str(i) + ')')
The Starting, Stopping, and Stepping Arguments to range()
The Starting, Stopping, and Stepping
Arguments to range()
Importing Modules

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

• 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).

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

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


Exception Handling
Exception Handling

• 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 execution
moves to the start of a
following except clause
if an error happens.
Exception Handling
• The reason
print(spam(1)) is
never executed is
because once the
execution jumps to
the code in the
except clause, it
does not return to
the try clause.
Instead, it just
continues moving
down as normal
A Short Program: Guess the Number

You might also like