CS 100

Logo

Scientific Computing

Activity 8 - Boolean expressions, logical operators, and if statements

Create a file boolean.py and save it to cs100/ch2.

  1. Let n=10 and k=20. For each of the following boolean expressions, determine whether it evaluates to True or False. First, write your answer in comments. Then, verify it by writing code to print out the result of the expression.
    1. (n == 10) and (k == 20)
    2. (n > 10) and (k == 20)
    3. (n > 10) or (k == 20)
    4. not( (n > 10) and (k == 20) )
    5. (not(n > 10)) and (not(k == 20))
    6. (n > 10) or (k == 10 or k != 5)
    7. (n < 20) or (k == 20)
    8. (n <= 10) and (k < 20)
    9. (n >= 10) and (k <= 20)
  2. Suppose you have a variable num which is initialized to some value. Give a boolean expression for each of the following situations:
    1. determine if num is between 5 and 10, inclusive.
    2. determine if num is greater than or equal to 0 and strictly less than 100.
    3. determine if num is strictly less than 100 and greater than or equal to 0, or it is equal to 200
    4. determine if num is a strictly positive number but not strictly larger than 150
  3. Consider these lines of code to answer the following questions. Write your answers in comments. Verify it by running the code.
    if x > 5:
     print("A")
    elif y < 10:
     print("B")
    elif x == 10:
     print("C")
    else:
     print("D")
    
    1. What prints out if initially x=8 and y=3?
    2. What prints out if initially x=5 and y=11?
    3. What prints out if initially x=10 and y=11?
    4. What prints out if initially x=0 and y=5?
    5. Is there any value of x or y that will print ā€œCā€?
  4. Import the random module at the top of your file. What is exactly do the following statements print? Why are the results different? Write your answer in comments.
    print( random.random() )
    print( random.random() )
    print( random.random() )
    
  5. Write a function that takes three integers as parameters and returns the largest integer.

If you finish early

  1. Complete problem 2.33 on page 72 of your book.

  2. Complete problem 2.35 on page 72 of your book.

How to submit

Submit your file to Moodle.