0
, 1
, 2
, 3
, ...1.23
, 2.45
, 5.0
, ...'hello'
, 'x'
, ...True
, False
True
and False
1 < 0
False
1 < 2
True
and
- test whether logical tests on the left and right side of operator are trueor
- test whether at least one of the logical tests on the left or right side of the operator are true1 < 2 and 2 < 3
True
1 < 2 and 2 < 2
False
1 < 2 or 2 < 2
True
1 < 1 or 2 < 2
False
if
Statements¶if
statement syntax in Python isn't quite as easy as our examples, but it's pretty close...if
statements begin with the if
keyword and are followed by a logical test and a colonif tired == 'Yes':
if
statement as an indented blockif tired == 'Yes':
go_to_bed()
Note that the actual word then is never used - it's implied by the indent
Interpret as:
if condition_holds:
execute_code()
if tired == 'Yes':
brush_teeth()
turn_off_lights()
go_to_bed()
tired == 'Yes'
is True
x = 'tired'
if x == 'tired':
print('Go to bed!')
Go to bed!
Describe what this statement is doing.
if denominator != 0:
quotient = numerator / denominator
Fill in the blanks to print the statement if x
is a negative number. Re-run multiple times.
import random
x = random.randint(-10, 10)
__ x _ __:
print(f'x = {x}, which is negative')
else
Statement¶else
statement must follow an if
statement and its indented then-blockif
statement, it begins with the else
keyword and is followed by a colon
if tired == 'Yes':
go_to_bed()
else:
read_a_book()
if
's then-block, there's also an indented block to be run if the else
path is takenelse
path be taken?
if tired == 'Yes':
go_to_bed()
else:
read_a_book()
else
path is taken in all cases when tired
is not equal to 'Yes'
Fill in the blanks to print the relevant statement for x
. Re-run multiple times.
import random
x = random.randint(-10, 10)
__ x _ __:
print('x is negative')
__:
print('x is positive')
elif
Statement¶elif
(else-if) statement can be used to add another if
statement in the execution pathif tired == 'Yes':
go_to_bed()
elif tired == 'A little':
rest_eyes()
else:
read_a_book()
elif
statements as you wantswitch
statement in other languages, this is Python's closest relativeFill in the blanks to print the relevant statement for x
.
import random
random.seed(7)
x = random.randint(-10, 10)
__ x _ __:
print('x is negative')
__ x _ __:
print('x is positive')
__:
print('x is zero')
if
-elif
-else
statements can be nested or combined to account for more complex logictired == 'Yes'
AND the time > 20:00
, you can nest if
statementsif tired == 'Yes':
if time > 20:00:
go_to_bed()
else
if tired == 'Yes':
if time > 20:00:
go_to_bed()
else:
take_a_nap()
if tired == 'Yes' and time > 20:00:
go_to_bed()
if tired == 'Yes' and time <= 20:00:
take_a_nap()
You will see a few common variants of our conditional test statement
All our examples thus far fall into this category:
x = 7
if x > 0:
print('x is positive')
x is positive
y = 'Ethan'
if y == 'Ethan':
print('y is not Brad')
y is not Brad
Sometimes we just want to know if a particular value exists in an object:
email = ['Ethan', 'Brad', 'spam']
if 'spam' in email:
print('You have spam in your email!')
You have spam in your email!
Sometimes we only want to operate on a particular type of object:
isinstance(email, list)
True
if isinstance(email, list):
print(f'You have {len(email)} email')
You have 3 email
x = 3
if isinstance(x, (int, float)):
print(x * 4)
else:
print('x is not a number')
12
Sometimes we want to operate on an object ___only if___ it contains values:
# the truthiness of empty objects are equivalent to False or 0
empty_list = []
if empty_list:
print('list is not empty')
else:
print('list is empty')
list is empty
# we can use this to do control flow for objects that contain information
email = ['Ethan', 'Brad', 'spam']
if email:
print('You have email!')
else:
print('Get back to work!')
You have email!
Sometimes we want to operate on an object if ___all___ or ___any___ of the values are True
:
email_is_spam = [False, False, True]
# use `all()` or `any()`
if all(email_is_spam):
print('All your emails are spam!')
elif any(email_is_spam):
print('At least one of your emails is spam!')
else:
print('No spam!')
At least one of your emails is spam!
numpy
package is really powerful for working with numeric data in Pythonimport numpy as np
where()
function from numpy
to conditionally create data within data framesimport pandas as pd
planes_df = pd.read_csv('../data/planes.csv')
planes_df.head(3)
tailnum | year | type | manufacturer | model | engines | seats | speed | engine | |
---|---|---|---|---|---|---|---|---|---|
0 | N10156 | 2004.0 | Fixed wing multi engine | EMBRAER | EMB-145XR | 2 | 55 | NaN | Turbo-fan |
1 | N102UW | 1998.0 | Fixed wing multi engine | AIRBUS INDUSTRIE | A320-214 | 2 | 182 | NaN | Turbo-fan |
2 | N103US | 1999.0 | Fixed wing multi engine | AIRBUS INDUSTRIE | A320-214 | 2 | 182 | NaN | Turbo-fan |
np.where()
to do soplanes_df['large'] = np.where(planes_df['seats'] > 150, 'Yes', 'No')
planes_df[['seats', 'large']].head(3)
seats | large | |
---|---|---|
0 | 55 | No |
1 | 182 | Yes |
2 | 182 | Yes |
True
, and the third parameter is the returned value if False
Describe what this statement is doing.
planes_df['modern'] = np.where(planes_df['year'] > 2008, 'Yes', 'No')
Create a variable large_and_modern
in planes_df
to indicate whether a plane is large and modern using np.where()
.
Are there any questions before we move on?