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

Python Notes

This document provides an overview of Python as a calculator, including arithmetic operators and their operations, data types like integers and floats, operator precedence, syntax and semantics, errors, variables, functions, and strings. Key points covered include the various arithmetic operators in Python and their expressions, built-in functions like abs(), dir(), and help(), defining custom functions, and using escape sequences in strings.

Uploaded by

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

Python Notes

This document provides an overview of Python as a calculator, including arithmetic operators and their operations, data types like integers and floats, operator precedence, syntax and semantics, errors, variables, functions, and strings. Key points covered include the various arithmetic operators in Python and their expressions, built-in functions like abs(), dir(), and help(), defining custom functions, and using escape sequences in strings.

Uploaded by

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

Python as a Calculator

Arithmetic Operators

Operator Operation Expression English description Result


+ addition 11 + 56 11 plus 56 67
- subtraction 23 - 52 23 minus 52 -29
* multiplication 4 * 5 4 multiplied by 5 20
** exponentiation 2 ** 5 2 to the power of 5 32
/ division 9 / 2 9 divided by 2 4.5
// integer division 9 // 2 9 divided by 2 4
% modulo (remainder) 9 % 2 9 mod 2 1

Types int and float

A type is a set of values and operations that can be performed on those values.

Two of Python's numeric types:

 int:integer
For example: 3, 4, 894, 0, -3, -18
 float: floating point number (an approximation to a real number)
For example: 5.6, 7.342, 53452.0, 0.0, -89.34, -9.5

Arithmetic Operator Precedence

When multiple operators are combined in a single expression, the operations are
evaluated in order of precedence.

Operator Precedence
** highest
- (negation)
*, /, //, %
+ (addition), - (subtraction) lowest

Syntax and Semantics

Syntax: the rules that describe valid combinations of Python symbols


Semantics: the meaning of a combination of Python symbols is the meaning of an
instruction — what a particular combination of symbols does when you execute it.

Errors

A syntax error occurs when we an instruction with invalid syntax is executed. For
example:
>>> 3) + 2 * 4
SyntaxError: invalid syntax

A semantic error occurs when an instruction with invalid semantics is executed. For
example:
>>> 89.4 / 0
Traceback (most recent call last):
File "", line 1, in
89.4 / 0
ZeroDivisionError: float division by zero

Python and Computer Memory


Computer Memory

For the purpose of this course, you may think of computer memory as a long list of
storage locations where each location is identified with a unique number and each
location houses a value. This unique number is called a memory address. Typically,
we will write memory addresses as a number with an "id" as a prefix to distinguish
them from other numbers (for example, id201 is memory address 201).

Variables are a way to keep track of values stored in computer memory. A variable is
a named location in computer memory. Python keeps variables in a separate list from
values. A variable will contain a memory address, and that memory address contains
the value. The variable then refers to the value. Python will pick the memory
addresses for you.

Terminology

A value has a memory address.


A variable contains a memory address.
A variable refers to a value.
A variable points to a value.
Example: Value 8.5 has memory address id34.
Variable shoe_size contains memory address id34.
The value of shoe_size is 8.5.
shoe_size refers to value 8.5.
shoe_size points to value 8.5.

Variables
Assignment statements

The general form of an assignment statement:


variable = expression

Example assignment statements:


>>> base = 20
>>> height = 12
>>> area = base * height / 2
>>> area
120.0

The rules for executing an assignment statement:

1. Evaluate the expression. This produces a memory address.


2. Store the memory address in the variable.

Variable names

The rules for legal Python names:

1. Names must start with a letter or _.


2. Names must contain only letters, digits, and _.

For Python, in most situations, the convention is to use pothole_case.

Visualizing Assignment Statements


On the Resources page is a link to a Python Visualizer that follows the model we use
to draw pictures of computer memory.

Consider this code:


x = 1
y = x + 2
x = 7

When we trace this in the visualizer and click button Forward twice, this is the result:

Clicking Forward once more results in this:

Notice that y's value did not change during this step.

Built-in Functions
Function Call

The general form of a function call:


function_name(arguments)
The rules for executing a function call:

1. Evaluate the arguments.


2. Call the function, passing in the argument values.

Terminology:

 Argument: a value given to a function


 Pass: to provide to a function
 Call: ask Python to evaluate a function
 Return: pass back a value

Example function calls:


>>> abs(-23)
23
>>> abs(56.24)
56.24

Function dir

Python has a set of built-in functions. To see the list of built-in functions,
run dir(__builtins__):
>>> dir(__builtins__)< br/> ['ArithmeticError', 'AssertionError',
'AttributeError', 'BaseException', 'BufferError', 'BytesWarning',
'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception',
'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError',
'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError',
'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None',
'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError',
'PendingDeprecationWarning', 'ReferenceError', 'ResourceWarning',
'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError',
'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError',
'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',
'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',
'__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all',
'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr',
'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr',
'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter',
'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash',
'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter',
'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next',
'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range',
'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted',
'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

Function help
To get information about a particular function, call help and pass the function as the
argument. For example:
>>> help(abs)
Help on built-in function abs in module builtins:
abs(...)
abs(number) -> number

Return the absolute value of the argument.

Optional arguments

In the description of function pow below, the square brackets around [, z] indicate
that the third argument is optional:
>>> help(pow)
Help on built-in function pow in module builtins:

pow(...)
pow(x, y[, z]) -> number

With two arguments, equivalent to x**y. With three arguments,


equivalent to (x**y) % z, but may be more efficient (e.g. for longs).

Function pow can be called with either two or three arguments:


>>> pow(2, 5)
32
>>> pow(2, 5, 3)
2

Defining Functions
Function Definitions

The general form of a function definition:

def function_name(parameters):
body

 def:a keyword indicating a function definition


 function_name: the function name
 parameters:
o the parameter(s) of the function, 0 or more and are separated by a
comma
o a parameter is a variable whose value will be supplied when the function
is called
 body:
o 1 or more statements, often ending with a return statement

Example of a function definition:


def f(x):
return x ** 2

return statement

The general form of a return statement:


return expression

The rules for executing a return statement:

1. Evaluate the expression. This produces a memory address.


2. Pass back that memory address to the caller. Exit the function.

Function Calls

Function calls are expressions and the result can be stored in a variable.

The general form of a function call:

function_name(arguments)

The rules for executing a function call:

1. Evaluate the arguments to produce memory addresses.


2. Store those memory addresses in the corresponding parameters.
3. Execute the body of the function.

Example of a function definition and function calls:


>>> def area(base, height):
return base * height / 2
>>> area(3, 4)
6.0
>>> result = area(10, 7.45)
>>> result
37.25
Saving your programs to ".py" files

We usually save our Python programs in ".py" files. A file can contain multiple
function definitions and other statements. Before calling a function from a ".py" file in
the shell in IDLE, you need to first execute Run -> Run Module, or else the shell will
not recognize the function call.

String Literal

A string literal is a sequence of characters. In Python, this type is called str. Strings
in Python start and end with a single quotes (') or double quotes ("). A string can be
made up of letters, numbers, and special characters. For example:
>>> 'hello'
'hello'
>>> 'how are you?'
'how are you?'
>>> 'short- and long-term'
'short- and long-term'

If a string begins with a single quote, it must end with a single quote. The same
applies to double-quoted strings. You can not mix the type of quotes.

Escape Sequences

To include a quote within a string, use an escape character (\) before it. Otherwise
Python interprets that quote as the end of a string and an error occurs. For example,
the following code results in an error because Python does not expect anything to
come after the second quote:
>>> storm_greeting = 'wow, you're dripping wet.'
SyntaxError: invalid syntax
The escape sequence \' indicates that the second quote is simply a quote, not the end
of the string:
>>> storm_greeting = 'Wow, you\'re dripping wet.'
"Wow, you're dripping wet."

An alternative approach is to use a double-quoted string when including a single-


quote within it, or vice-versa. Single- and double-quoted strings are equivalent. For
example, when we used double-quotes to indicate the beginning and end of the string,
the single-quote in you're no longer causes an error:
>>> storm_greeting = "Wow, you're dripping wet."
"Wow, you're dripping wet."
String Operators

Expression Description Example Output


str1 + str2 concatenate str1 and str1 print('ab' + 'c') abc
str1 * int1 concatenate int1 copies of str1 print('a' * 5) aaaaa
int1 * str1 concatenate int1 copies of str1 print(4 * 'bc') bcbcbcbc

Note: concatenate means to join together

The * and + operands obey by the standard precedence rules when used with strings.

All other mathematical operators and operands result in a TypeError.

Function print

Python has a built-in function named print that displays messages to the user. For
example, the following function call displays the string "hello":
>>> print("hello")
hello
In the output above, notice that hello is displayed without the quotation marks. The
quotes are only for Python's internal string formatting and are not seen by the user.

The print function may also be called with a mathematical expression for an
argument. Python evaluates the mathematical expression first and then displays the
resulting value to the user. For example:
>>> print(3 + 7 - 3)
7

Finally, print can take in more than one argument. Each pair of arguments is
separated by a comma and a space is inserted between them when they are displayed.
For example:
>>> print("hello", "there")
hello there

return vs. print

Recall: The general form of a return statement:


return expression
When a return statement executes, the expression is evaluated to produce a memory
address.

 What is passed back to the caller?


That memory address is passed back to the caller.
 What is displayed?
Nothing!

An example of return:
>>> def square_return(num):
return num ** 2
>>> answer_return = square_return(4)
>>> answer_return
16

The general form of a print function call:


print(arguments)

When a print function call is executed, the argument(s) are evaluated to produce
memory address(es).

 What is passed back to the caller?


Nothing!
 What is displayed?
The values at those memory address(es) are displayed on the screen.

An example of print:
>>> def square_print(num):
print("The square of num is", num ** 2)
>>> answer_print = square_print(4)
The square num is 16
>>> answer_print
>>>

Function input

The function input is a built-in function that prompts the user to enter some input. The
program waits for the user to enter the input, before executing the subsequent
instructions. The value returned from this function is always a string. For example:
>>> input("What is your name? ")
What is your name? Jen
'Jen'
>>> name = input("What is your name? ")
What is your name? Jen
>>> name
'Jen'
>>> location = input("What is your location? ")
What is your location? Toronto
>>> location
'Toronto'
>>> print(name, "lives in", location)
Jen lives in Toronto
>>> num_coffee = input("How many cups of coffee? ")
How many cups of coffee? 2
>>> num_coffee
'2'

Operations on strings

Operation Description Example Output


str1 + str2 concatenate str1 and str1 print('ab' + 'c') abc
str1 * int1 concatenate int1 copies of str1 print('a' * 5) aaaaa
int1 * str1 concatenate int1 copies of str1 print(4 * 'bc') bcbcbcbc

Triple-quoted strings

We have used single- and double- quotes to represent strings. The third string format
uses triple-quotes and a triple-quoted string can span multiple lines. For example:
>>> print(''' How
are
you?''')
How
are
you?

Escape Sequences

Python has a special character called an escape character: \. When the escape
character is used in a string, the character following the escape character is treated
differently from normal. The escape character together with the character that follows
it is an escape sequence. The table below contains some of Python's commonly used
escape sequences.

Escape
Name Example Output
Sequence
\n newline (ASCII linefeed - print('''How How
are are
LF) you?''') you?
3 4
\t
tab (ASCII horizontal tab - print('3\t4\t5') 5
TAB)
print('\\') \
\\ backslash (\)
print('don\'t') don't
\' single quote (')
print("He He says,
\" double quote (") says, \"hi\".") "hi".

Docstrings and Function help


Built-in function help displays the docstring from a function definition. For example,
consider this function:
def area(base, height):
"""(number, number) -> number

Return the area of a triangle with dimensions base


and height.
"""

return base * height / 2

Calling help on function area produces this output:


>>> help(area)
Help on function area in module __main__:

area(base, height)
(number, number) -> number

Return the area of a triangle with dimensions base


and height.

Function Design Recipe


The Six Steps

1. Examples
o What should your function do?
o Type a couple of example calls.
o Pick a name (often a verb or verb phrase): What is a short answer to
"What does your function do"?
2. Type Contract
o What are the parameter types?
o What type of value is returned?
3. Header
o Pick meaningful parameter names.
4. Description
o Mention every parameter in your description.
o Describe the return value.
5. Body
o Write the body of your function.
6. Test
o Run the examples.

Applying the Design Recipe

The problem:

The United States measures temperature in Fahrenheit and Canada measures it in


Celsius. When travelling between the two countries it helps to have a conversion
function. Write a function that converts from Fahrenheit to Celsius.

1. Examples
2. >>> convert_to_celsius(32)
3. 0
4. >>> convert_to_celsius(212)
5. 100
6.
7. Type Contract
8. (number) -> number
9.
10.Header
11. def convert_to_celsius(fahrenheit):
12.
13.Description
14. Return the number of Celsius degrees equivalent to fahrenheit
degrees.
15.
16.Body
17. return (fahrenheit - 32) * 5 / 9
18.
19.Test
20. Run the examples.
21.
Putting it all together:
def convert_to_celsius(fahrenheit):
''' (number) -> number

Return the number of Celsius degrees equivalent to fahrenheit degrees.

>>> convert_to_ccelsius(32)
0
>>> convert_to_celsius(212)
100
'''

return (fahrenheit - 32) * 5 / 9

Function Reuse
Calling functions within other function definitions

The problem: Calculate the semi-perimeter of a triangle.

The approach: Function semiperimeter calls function perimeter.


def perimeter(side1, side2, side3):
'''(number, number, number) -> number

Return the perimeter of a triangle with sides of length


side1, side2 and side3.

>>> perimeter(3, 4, 5)
12
>>> perimeter(10.5, 6, 9.3)
25.8
'''
return side1 + side2 + side3

def semiperimeter(side1, side2, side3):


'''(number, number, number) -> float

Return the perimeter of a triangle with sides of


length side1, side2 and side3.

>>> semiperimeter(3, 4, 5)
6.0
>>> semiperimeter(10.5, 6, 9.3)
12.9
'''
return perimeter(side1, side2, side3) / 2

Calling functions within other function calls


The problem: One triangle has a base of length 3.8 and a height of length 7.0. A
second triangle has a base of length 3.5 and a height of length 6.8. Calculate which of
two triangles' areas is biggest.

The approach: Pass calls to function area as arguments to built-in function max.
max(area(3.8, 7.0), area(3.5, 6.8))

Functions, Variables, and the Call Stack


Understanding Scope

Below is an explanation and review of the example used in the video.


def convert_to_minutes(num_hours):
""" (int) -> int
Return the number of minutes there are in num_hours hours.
"""
minutes = num_hours * 60
return minutes

def convert_to_seconds(num_hours):
""" (int) -> int
Return the number of seconds there are in num_hours hours.
"""
minutes = convert_to_minutes(num_hours)
seconds = minutes * 60
return seconds

seconds = convert_to_seconds(2)

Python defines the first two functions, creates objects for them in the heap, and, in the
stack frame for the main program, creates variables that refer to those function
objects.

After that, it executes the assignment statement on line 16. The right-hand side of the
assignment statement is a function call so we evaluate the argument, 2, first. The
frame for convert_to_seconds will appear on the call stack. The parameter, num_hours,
will refer to the value 2.

The first statement in function convert_to_seconds is an assignment statement. Again,


we evaluate the expression on the right-hand side. This is a function call so we
evaluate the argument, num_hours. This produces the value 2. A stack frame for
function convert_to_minutes is created on the call stack. Python stores the memory
address of 2 in the parameter for convert_to_minutes, which also happens to be
called num_hours.

We now see that there are two variables called num_hours in the call stack; one is
in convert_to_minutes and the other is in convert_to_seconds.

The next line of code Python executes is minutes = num_hours * 60. However, which
instance of num_hours will be used? Python always uses the variable in the current
stack frame. With an assignment statement, if the variable does not exist in the current
stack frame, Python creates it. So, once num_hours * 60 is evaluated,
variable minutes is created in the current stack frame.
The last line of the function is return minutes. Once this statement is complete,
Python will return to the frame just underneath the top of the call stack.

So, Python is going to produce the value 120, remove the current stack frame, create a
new variable called minutes in the stack frame for convert_to_seconds, and store the
memory adress of 120 in that variable.

Python then executes seconds = minutes * 60. Python evaluates the right-hand side,
which produces 7200, and stores the memory address of that value in variable seconds.
Since this variable does not exist yet, Python creates it in the current stack
frame.

Next is a return statement. Like we saw above, that is going to return control back to
the the main module.

Once the frame for convert_to_seconds is removed, the assignment statement on line
16 (which has been paused a long time!) is completed, and a new variable seconds is
created in the stack frame for the main program.

Notes and assignment and return statements

Assignment statement and computer memory


variable = expression
If a variable does not exist in the current stack frame, Python creates it.

Return statement and computer memory


return expression

In addition to evaluating the expression and yielding its value, return also erases the
stack frame on top of the call stack.

Type bool: Booleans in Python


Boolean values

The Python type bool has two values: True and False.

Comparison operators

The comparison operators take two values and produce a Boolean value.

Description Operator Example Result of example


less than < 3 < 4 True
greater than > 3 > 4 False

equal to == 3 == 4 False

greater than or equal to >= 3 >= 4 False

less than or equal to <= 3 <= 4 True

not equal to != 3 != 4 True

Logical operators

There are also three logical operators that produce Boolean values: and, or, and not.

Description Operator Example Result of example


not not not (80 >= 50) False

and and (80 >= 50) and (70 <= 50) False

or or (80 >= 50) or (70 <= 50) True

The and Logic Table

The and operator produces True if and only if both expressions are True.

As such, if the first operand is False, the second condition will not even be checked,
because it is already known that the expression will produce False.

expr1 expr2 expr1 and expr2


True True True
True False False
False True False
False False False

The or Logic Table

The or operator evaluates to True if and only if at least one operand is True.
As such, if the first operand is True, the second condition will not even be checked,
because it is already known that the expression will produce True.

expr1 expr2 expr1 or expr2


True True True
True False True
False True True
False False False

The not Logic Table

The not operator evaluates to True if and only if the operand is False.

expr1 not expr1


True False
False True

Double-negation can be simplified. For example, the expression not not (4 == 5) can
be simplified to 4 == 5.

Order of Precedence for Logical Operators

The order of precedence for logical operators is: not, and, then or. We can override
precedence using parentheses and parentheses can also be added to make things easier
to read and understand.

For example, the not operator is applied before the or operator in the following code:
>>> grade = 80
>>> grade2 = 90
>>> not grade >= 50 or grade2 >= 50
True

Parentheses can be added to make this clearer: (not grade >= 50) or (grade2 >= 50)

Alternatively, parentheses can be added to change the order of operations: not


((grade >= 50) or (grade2 >= 50))
Converting between int, str, and float
str

Builtin function str takes any value and returns a string representation of that value.
>>> str(3)
'3'
>>> str(47.6)
'47.6'

int

Builtin function int takes a string containing only digits (possibly with a leading
minus sign -) and returns the int that represents. Function int also
converts float values to integers by throwing away the fractional part.
>>> int('12345')
12345
>>> int('-998')
-998
>>> int(-99.9)
-99

If function int is called with a string that contains anything other than digits,
a ValueError happens.
>>> int('-99.9')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '-99.9'

float

Builtin function float takes a string containing only digits and zero or one decimal
points (possibly with a leading minus sign -) and returns the float that represents.
Function float also converts int values to floats.
>>> float('-43.2')
-43.2
>>> float('432')
432.0
>>> float(4)
4.0

If function float is called with a string that can't be converted, a ValueError happens.
>>> float('-9.9.9')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '-9.9.9'

Import: Using Non-Builtin Functions


Modules

Python contains many functions, but not all of them are immediately available as
builtin functions. Instead of being available as builtins, some functions are saved in
different modules. A module is a file containing function definitions and other
statements.

We may also define our own modules with our own functions.
import

In order to gain access to the functions in a module, we must import that module.

The general form of an import statement is:


import module_name

To access a function within a module, we use:


module_name.function_name

For example, we can import the Python module math and call the function sqrt from
it:
import math

def area2(side1, side2, side3):


semi = semiperimeter(side1, side2, side3)
area = math.sqrt(semi * (semi - side1) * (semi - side2) * (semi -
side3))
return area

In addition to importing Python's modules, we can also import the modules that we
write. For example, to use the functions from triangle.py (from the video) in another
module, we would import triangle. A module being imported should be in the same
directory as the module importing it.
The if statement
If statements can be used to control which instructions are executed. Here is the
general form:
if expression1:
body1
[elif expression2: 0 or more clauses
body2]
[else: 0 or 1 clause
bodyN]

elif stands for "else if", so this forms a chain of conditions.

To execute an if statement, evaluate each expression in order from top to bottom. If


an expression produces True, execute the body of that clause and then skip the rest
open the if statement. If there is an else, and none of the expressions produce True,
then execute the body of the else.

For example, given this function:


def report_status(scheduled_time, estimated_time):
""" (float, float) -> str """
if scheduled_time == estimated_time:
return 'on time'
elif scheduled_time > estimated_time:
return 'early'
else:
return 'delayed'
In the shell:

>>> report_status(14.3, 14.3)


'on time'
>>> report_status(12.5, 11.5)
'early'
>>> report_status(9.0, 9.5)
'delayed'

A note on None

When execution of a function body ends without having executed a return statement,
the function returns value None. The type of None is NoneType.

For example, consider this function:


def report_status(scheduled_time, estimated_time):
""" (float, float) -> str
Return the flight status (on time, early, delayed) for a flight that was
scheduled to arrive at scheduled_time, but is now estimated to arrive
at estimated_time.

Pre-condition: 0.0 <= scheduled_time < 24.0 and 0.0 <= estimated_time <
24.0

>>> report_status(14.3, 14.3)


'on_time'
>>> report_status(12.5, 11.5)
'early'
>>> report_status(9.0, 9.5)
'delayed'
"""

if scheduled_time == estimated_time:
return 'on time'

In the shell:

>>> report_status(14,3, 14.3)


'on time'
>>> report_status(12.5, 11.5)
>>> print(report_status(12.5, 11.5))
None

Because the type of None is NoneType, not str, this breaks the Type Contract. To fix
this, we would need to complete the rest of the function.

No if Required
It is common for new programmers to write code like the following:
def is_even(num):
""" (int) -> bool
Return whether num is even.
"""

if num % 2 == 0:
return True
else:
return False

This works, but is stylistically questionable. It's also more typing and reading than is
necessary!

num % 2 == 0 already produces True or False, so that expression can be used with
the return statement:
def is_even(num):
""" (int) -> bool
Return whether num is even.
"""

return num % 2 == 0

Structuring if Statements
if-elif vs. if-if

An if statement with an elif clause is a single statement. The expressions are


evaluated from top to bottom until one produces True or until there are no expressions
left to evaluate. When an expression produces True, the body associated with it is
executed and then the if statement exits. Any subsequent expressions are ignored. For
example:
grade1 = 70
grade2 = 80

if grade1 >= 50:


print('You passed a course with grade: ', grade1)
elif grade2 >= 50:
print('You passed a course with grade: ', grade2)

The if statement condition (grade1 >= 50) evaluates to True, so the body associated
with the if is executed and then the if exits. The elif condition is not even evaluated
in this case.

It is possible for if statements to appear one after another in a program. Although they
are be adjacent to each other, they are completely independent of each other and it is
possible for the body of each if to be executed. For example:
grade1 = 70
grade2 = 80

if grade1 >= 50:


print('You passed a course with grade: ', grade1)
if grade2 >= 50:
print('You passed a course with grade: ', grade2)

In the program above, the condition associated with the first if statement (grade1 >=
50) produces True, so the body associated with it is executed. The condition associated
with the second if statement (grade2 >= 50) also produces True, so the body
associated with it is also executed.
Nested ifs

It is possible to place an if statement within the body of another if statement. For


example:
if precipitation:
if temperature > 0:
print('Bring your umbrella!')
else:
print('Wear your snow boots and winter coat!)

The statement above can be simplified by removing some of the nesting. The
message 'Bring your umbrella!' is printed only when both of the if statement
conditions are True. The message 'Wear your snow boots and winter coat!' is
printed only when the outer if condition is True, but the inner if condition is False.
The following is equivalent to the code above:
if precipitation and temperature > 0:
print('Bring your umbrella')
elif precipitation:
print('Wear your snow boots and winter coat!')

You might also like