Week 3: Conditionals and Boolean Logic

Week 3 Goals

  • Learn the Boolean data type

  • Learn the comparison operators: ==, !=, <, <=, >, >=

  • Learn the logical operators: and, or, not

  • Learn to use if/elif/else statements to execute code conditionally

  • Learn the % operator for formatting strings

Week 3 Code

  • booleans.py: practice with Boolean variables and operators

  • logic_tests.py: testing your understanding of relational operators

  • leapyear.py: write a program to determine whether a year is a leap year

  • conditionals.py: practice with conditional statements

  • phase.py: write a program to determine whether water is a solid, liquid, or gas

  • movies.py: write a program to calculate movie ticket prices

  • stringformatting.py: practice with formatting string output

Week 3 Concepts

Boolean variables

A Boolean variable can have one of two values: True or False:

is_logged_in = True
print(is_logged_in) # prints "True"

is_admin = False
print(is_admin) # prints "False"

Comparison operators

We can use comparison operators to compare two values and generate a Boolean value:

x = 5
is_positive = x > 0
print(is_positive) # prints "True"

is_even = x % 2 == 0
print(is_even) # prints "False"

The above examples use > for "greater than" and == for "equals". The other comparison operators are:

  • < for "less than"

  • <= for "less than or equal to"

  • >= for "greater than or equal to"

  • != for "not equal to"

Logical operators

We can use logical operators to perform operations on Boolean values and generate other Boolean values.

The not operator inverts or negates a single Boolean value:

is_weekend = True
print(not is_weekend) # prints "False"

The or operator takes two Booleans as its operands and evaluates to True if either is true, and False otherwise:

x = 5
result = (x > 0) or (x == 3)
print(result) # prints "True"

result = (x > 0) or (x < 10)
print(result) # prints "True"

result = (x == 4) or (x == 11)
print(result) # prints "False"

The and operator takes two Booleans as its operands and evaluates to True if both are true, and False otherwise:

x = 5
result = (x > 0) and (x < 10)
print(result) # prints "True"

result = (x > 0) and (x < 3)
print(result) # prints "False"

Conditional statements

Boolean values (and expressions that generate Boolean values) can be used to execute code conditionally. This means that, depending on the values of variables, different parts of the code may run each time it is executed.

An if statement is used to evaluate a Boolean expression and then execute the body of the if-statement if the expression evaluates to true:

value = int(input("Enter a value: "))
if (value > 0):
    print("The value is positive")
print("The end.")

In the above example, the code will only print "The value is positive" if the condition value > 0 is true, but will not print it if it is false. However, the program will print "The end." regardless of whether the value is positive.

An else statement can be used to provide code to execute if the condition for the if statement is false:

value = int(input("Enter a value: "))
if (value > 0):
    print("The value is positive")
else:
    print("The value is not positive")
print("The end.")

Now the code will print "The value is positive" if the condition is true, but if the condition value > 0 is false, then the else-statement will be run and the program will print "The value is not positive".

An elif statement (short for "else if") can be used to create chains of if and else statements to check for multiple conditions:

value = int(input("Enter a value: "))
if (value > 0):
    print("The value is positive")
elif (value < 0):
    print("The value is negative")
else:
    print("The value is zero")
print("The end.")

In this case, if the first condition (value > 0) is false, then the code will check the second condition (value < 0): if that is true, then the code will print "The value is negative". However, if the second condition is also false, then the code will execute the else-statement and print "The value is zero".

String formatting

Until now we have been using string concatenation to dynamically generate strings:

name = input("Enter your name: ")
age = input("Enter your age: ")
next_age = int(age) + 1
print("Hi, " + name + ", nice to meet you." + \
    "You'll turn " + next_age + " on your next birthday!")

This can become cumbersome and error-prone when we have strings that require lots of concatenation, so a more concise way is to use the string formatting operator %, which takes a template (or "format") string and then replaces placeholder terms with specific values:

name = input("Enter your name: ")
age = input("Enter your age: ")
next_age = int(age) + 1
format = "Hi, %s, nice to meet you. You'll turn %d on your next birthday!"
msg = format % (name, next_age)
print(msg)

In the format string, the %s is a placeholder for a string, and %d is the placeholder for a decimal (base-10) integer. The value of the msg variable is created by applying the values of name and next_age to the template.

We can also use string formatting to indicate how much space a string should take when being displayed, e.g. by adding spaces before or after it, or the precision (number of values after the decimal point) of a floating point value:

num = 2.718281828
print("the number is %.3f" % (num) ) # prints "the number is 2.718"

In the above example, the %.3f indicates this is a placeholder for a floating point number and that we want to display three values after the decimal point.