These are the basic data types that constitute all of the more complex data structures in python. The basic data types are the following:
Booleans represent the truth or success of a statement, and are commonly used for branching and checking status in code.
They can take two values: True
or False
.
bool_1 = True
bool_2 = False
print(bool_1)
print(bool_2)
True False
If you remember from our strings session, we could execute a command that checks in a string appears within another. For example:
lookfor = "Trump"
text = """Three American prisoners freed from North Korea arrived here early
Thursday to a personal welcome from President Trump, who traveled to an air
base in the middle of the night to meet them."""
trump_in_text = lookfor in text
print("Does Trump appear in the text?", trump_in_text)
Does Trump appear in the text? True
Frequently, one wants to combine or modify boolean values. Python has several operations for just this purpose:
not a
: returns the opposite value of a
.a and b
: returns true if and only if both a
and b
are true.a or b
: returns true either a
or b
are true, or both.See LPTHW Exercise 27
Like mathematical expressions, boolean expressions can be nested using parentheses.
var1 = 5
var2 = 6
var3 = 7
Consider the outcomes of the following examples
print(var1 + var2 == 11)
True
print(var2 + var3 == 13)
True
print(var1 + var2 == 11 and var2 + var3 == 13)
True
print(var1 + var2 == 12 and var2 + var3 == 13)
False
print(var1 + var2 == 12 or var2 + var3 == 13)
True
print((not var1 + var2 == 12) or (var2 + var3 == 14))
True
# 1
True and True
True
# 2
False and True
False
# 3
1 == 1 and 2 == 1
False
# 4
"test" == "test"
True
# 5
1 == 1 or 2 != 1
True
# 6
True and 1 == 1
True
# 7
False and 0 != 0
False
# 8
True or 1 == 1
True
# 9
"test" == "testing"
False
# 10
1 != 0 and 2 == 1
False
# 11
"test" != "testing"
True
# 12
"test" == 1
False
Now Complete Exercises 12-20 in 28. But this time let's examine how to evaluate these expressions on a step by step basis.
# 13
not (True and False)
True
# 14
not (1 == 1 and 0 != 1)
False
# 15
not (10 == 1 or 1000 == 1000)
False
# 16
not (1 != 10 or 3 == 4)
False
# 17
not ("testing" == "testing" and "Zed" == "Cool Guy")
True
# 18
1 == 1 and (not ("testing" == 1 or 1 == 0))
True
# 19
"chunky" == "bacon" and (not (3 == 4 or 3 == 3))
False
# 20
3 == 3 and (not ("testing" == "testing" or "Python" == "Fun"))
False
# bonus
3 != 4 and not ("testing" != "test" or "Python" == "Python")
False
Now let's try to write the boolean expressions that will evaluate different conditions, given a set of other variables.
# To drink alcohol, you need to be above 21 yo
age = 18
# your code here, replace "False" with an expression
can_drink_alcohol = False
print(f"Age: {age}; can drink alcohol? {can_drink_alcohol}")
Age: 18; can drink alcohol? False
# To get a driving license you need to be above 16 yo
age = 18
# your code here, replace "False" with an expression
can_get_driving_license = False
print(f"Age: {age}; can get driving license? {can_get_driving_license}")
Age: 18; can get driving license? False
# You need to be a US Citizen to have a passport
us_citizen = True
# your code here, replace "False" with an expression
can_get_us_passport = False
print(f"US Citizen: {us_citizen}; can get US passport? {can_get_us_passport}")
US Citizen: True; can get US passport? False
# You need to be above 18 and a US Citizen
age = 18
us_citizen = True
# your code here, replace "False" with an expression
can_vote = False
print(f"US Citizen: {us_citizen}; Age: {age}\nCan Vote? {can_vote}")
US Citizen: True; Age: 18 Can Vote? False
# You need to be above 35, a US Citizen, and born in the US
age = 70
born_in_us = True
us_citizen = True
# your code here, replace "False" with an expression
can_be_president = False
print(f"US Citizen: {us_citizen}; Age: {age}; Born in US? {born_in_us}")
print(f"Can be president? {can_be_president}")
US Citizen: True; Age: 70; Born in US? True Can be president? False
# Can you become citizen?
# You qualify for a citizen if any of the following holds
# * Your parents are US Citizens and you are under 18
# * You have been born in the US
age = 19
parents_citizens = False
born_in_us = True
# your code here, replace "False" with an expression
citizen_eligible = False
print(f"Citizen parents: {parents_citizens}")
print(f"Age: {age}")
print(f"Born in US? {born_in_us}")
print(f"Eligible for Citizen? {citizen_eligible}")
Citizen parents: False Age: 19 Born in US? True Eligible for Citizen? False
Traversing over data and making decisions based upon data are a common aspect of every programming language, known as control flow. Python provides a rich control flow, with a lot of conveniences for the power users. Here, we're just going to talk about the basics, to learn more, please consult the documentation.
A common theme throughout this discussion of control structures is the notion of a "block of code." Blocks of code are demarcated by a specific level of indentation, typically separated from the surrounding code by some control structure elements, immediately preceeded by a colon, :
. We'll see examples below.
Finally, note that control structures can be nested arbitrarily, depending on the tasks you're trying to accomplish.
See also LPTHW, Exp 29, 30, and 31.
If statements are perhaps the most widely used of all control structures. An if statement consists of a code block and an argument. The if statement evaluates the boolean value of it's argument, executing the code block if that argument is true.
execute = False
if execute:
print("Of course!")
print("This will execute as well")
execute = False
if execute:
print("Me? Nobody?")
print("Really? Nobody?")
print("I am not nested, I will show up!")
I am not nested, I will show up!
And here is an if
statement paired with an else
.
lookfor = "Trump"
text = """
Three American prisoners freed from North Korea arrived here early Thursday
to a personal welcome from President Trump, who traveled to an air
base in the middle of the night to meet them.
"""
if lookfor in text:
print(lookfor, "appears in the text")
else:
print(lookfor, "does not appear in the text")
Trump appears in the text
lookfor = "Obama"
text = """
Three American prisoners freed from North Korea arrived
here early Thursday to a personal welcome from President Trump,
who traveled to an air base in the middle of the night to meet them.
"""
if lookfor in text:
print(lookfor, "appears in the text")
else:
print(lookfor, "does not appear in the text")
Obama does not appear in the text
Each argument in the above if statements is a boolean expression. Often you want to have alternatives, blocks of code that get evaluated in the event that the argument to an if statement is false. This is where elif
(else if) and else come in.
An elif
is evaluated if all preceding if or elif arguments have evaluated to false. The else statement is the last resort, assigning the code that gets executed if no if or elif above it is true. These statements are optional, and can be added to an if statement in any order, with at most one code block being evaluated. An else will always have it's code be executed, if nothing above it is true.
status = "Senior"
if status == "Freshman":
print("Hello newbie!")
print("How's college treating you?")
elif status == "Sophomore":
print("Welcome back!")
elif status == "Junior":
print("Almost there, almost there")
elif status == "Senior":
print("You can drink now! You will need it.")
elif status == "Senior":
print("The secret of life is 42. But you will never see this")
else:
print("Are you a graduate student? Or (gasp!) faculty?")
You can drink now! You will need it.
age = 20
if age >= 21:
print("You are above 21, you can drink")
else:
print("You are too young. Wait for", 21 - age, "years")
You are too young. Wait for 1 years
age = 18
if age >= 21:
print("You are above 21, you can drink")
else:
print("You are too young. Wait for", 21 - age, "years")
You are too young. Wait for 3 years
age = 18
has_driving_license = False
if age < 16:
print("You are too young to drive")
else:
if has_driving_license:
print("You can drive")
else:
print("You are old enough to drive, but you need a driving license")
You are old enough to drive, but you need a driving license
age = 15
has_driving_license = True
if age >= 16 and has_driving_license:
print("You can drive")
elif age >= 16 and not has_driving_license:
print("You are old enough to drive, but you need a driving license")
else:
print("You are too young to drive")
You are too young to drive
age = 18
has_driving_license = False
if age < 16:
print("You are too young to drive")
else:
if has_driving_license:
print("You can drive")
else:
print("You are old enough to drive, but you need a driving license")
You are old enough to drive, but you need a driving license
age = 18
has_driving_license = False
if age >= 16 and has_driving_license:
print("You can drive")
elif age >= 16 and not has_driving_license:
print("You are old enough to drive, but you need a driving license")
else:
print("You are too young to drive")
You are old enough to drive, but you need a driving license
age = 15
us_citizen = False
registered = True
if age >= 18 and us_citizen and registered:
print("You can vote")
else:
print("You cannot vote")
# Now let's explain the reason
if age < 18:
print("You are below 18")
if not us_citizen:
print("You are not a US citizen")
if not registered:
print("You are not registered")
You cannot vote You are below 18 You are not a US citizen
age = 15
us_citizen = False
registered = True
if age >= 18 and us_citizen and registered:
print("You can vote")
else:
print("You cannot vote")
if age < 18:
print("You are below 18")
if not us_citizen:
print("You are not a US citizen")
if not registered:
print("You are not registered")
You cannot vote You are below 18 You are not a US citizen
age = 15
parents_citizens = False
born_in_us = False
if (age < 18 and parents_citizens) or born_in_us:
print("You can become a US citizen")
else: # none of the two conditions around the or were True
print("You cannot become a US citizen")
if not born_in_us:
print("You were not born in the US")
if not (age < 18 and parents_citizens):
print("You need to be below 18 and your parents need to be citizens")
You cannot become a US citizen You were not born in the US You need to be below 18 and your parents need to be citizens
age = 16
parents_citizens = True
born_in_us = False
if (age < 18 and parents_citizens) or born_in_us:
print("You can become a US citizen")
else: # none of the conditions were true
if not born_in_us:
print("You were not born in the US")
if not (age < 18 and parents_citizens):
print("You need to be below 18 and your parents need to be citizens")
You can become a US citizen