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

Get Week 3 In-class Code

To copy over the week 3 in-class example programs, do the following (If you have trouble with either of these steps, ask a Ninja or your professor for help):

  1. Create a w03-conditionals subdirectory in your cs21/inclass directory, and cd into it:

    $ cd ~/cs21/inclass
    $ mkdir w03-conditionals
    $ cd w03-conditionals
    $ pwd
    /home/yourusername/cs21/inclass/w03-conditionals
  2. Copy over the week 3 files into your w03-conditionals subdirectory (check that they copied successfully copied by running ls:

    $ cp ~admin21/public/w03-conditionals/* ./
    $ ls
    booleans.py conditionals.py leapyear.py logic_tests.py movies.py phase.py stringformatting.py whileloops.py

Editing and Running Python programs

To open and edit a Python source code file, in a terminal, run the code editor with the name of the file you want to edit (e.g., prog.py):

$ code prog.py

To run a Python program, in a terminal, invoke the Python interpreter (python3) followed by the name of the file with the Python program you want to run (e.g. prog.py):

$ python3 prog.py

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

  • whileloops.py: practice with while-loops

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.

While-Loops

One limitation of for-loops that we have seen previously is that we need to know in advance how many times the loop will run, based on the number of values in the sequence over which we’re iterating.

If we don’t know in advance how many times the loop should run, but want to keep looping as long as some condition is true, an alternative is to use a while-loop, which will keep looping until the condition is false.

For instance, this code keeps looping while the value is negative or zero, and stops looping once the user enters a positive value:

value = -1
while (value <= 0):
    value = int(input("Please enter a positive number: "))
print("the number is " + str(value))

Once we exit the loop, we know that value must be positive, otherwise we’d still be looping!