Skip to main content
Chemistry LibreTexts

2.5: Boolean Expressions and Selection Statements

  • Page ID
    206263
  • hypothes.is tag: s20iostpy05ualr
    Download Assignment: S202py05

     

    Learning Objectives

    Students will be able to:

    Content:

    • Explain the three types of programming structures
    • Explain how conditional operators and logical operators are used in programming
    • Use conditional operators with strings and numeric values
    • Implement the Python syntax of an if/elif/else statement
    • Determine good test data for programs that include if/elif/else statements

    Process:

    • Write code that includes if statements and if/elif/else statements
    • Write correct Boolean expressions and compound expressions

    Prior Knowledge

    • Python concepts from Activities 1-4
    • Understanding of flowchart input symbols

    Further Reading

     

    Model 1: Conditional Operators

    Conditional operators, also known as relational operators, are used to compare the relationship between two operands. Expressions that can only result in one of two answers are known as Boolean expression.

    In[1]: 34<56
    Out[1]: True
    1. Determine the meaning of each of the following conditional operators. If you are not sure of the meaning of any symbol, create some example expressions, type them into the python shell of your Thonny IDE (see figure to the right) and examine the results.


          a.         <          _____________ __                    b.         >          ________________

          c.         <=        _____________ __                    d.         >=        ________________

          e.         !=         _____________ __                    f.          ==        ________________

     

    1. What is the result of each of the following expressions given the following variable assignments?

         x = 4,    y = 5,    z = 4

    Expression Boolean Expession
    X>Y  
    X<Y  
    X==Y  
    X!=Y  
    X>=Z  
    X<=Z  
    X+Y>2*X  
    Y*X-Z!=4%4+16  
    pow(x,2)==abs(-16)  

    3.  What is the result of the following expressions given the following variable assignments?

    word1 = "hello", word2 = "good-bye"

    Expression Boolean Expression
    word1==word2  
    word1!=word2  
    word1<word2  
    word1>=word2  

    4.  Explain how the conditional operators are used when the operands are strings.
     

    5.  What are the only two possible answers to all of the expressions in questions 2 and 3?


    Model 2:  Programming Structures  

    flow charts

    6.   Each of the flowchart symbols in the chart above represents lines or segments of code.   After examining the chart, write a description of:

        a.  sequence structure
        b.  decision or branching structure
        c.   looping structure
     

    7.  Which structure best describes the types of Python programs you have written so far? Do you think this structure is the best structure to use for all programs?  Why or why not?
     

    8.  Which structure allows the programmer to create code that decides what code is executed?


    Model 3: IF/ELSE Statement

    Flowchart Python Program 5.1
    flowchart
    # Programmer: Monty Python
    # Date: Some time in the past
    # Program showing IF statement
    
    examScore = 95
    if examScore >= 93:
        print("Excellent!")

     

    9.   Consider Model 3 above:

    a. What is the Python code equivalent of the diamond flowchart symbol in the program above?

    b. What is the output of the program?

    c. What would the output of the program be if the value of the variable examScore was set to 85?

     

    10.  Execute the two following python programs by copying and pasting into your editor window of Thonny IDE.

    Python Program 5.2 Python Program 5.3
    # Programmer: Monty Python
    # Date: Some time in the past
    # Program showing IF statement
    
    examScore = 85
    if examScore >= 93:
        print("Excellent!")
        print("Done! ")

     

    # Programmer: Monty Python
    # Date: Some time in the past
    # Program showing IF statement
    
    examScore = 85
    if examScore >= 93:
        print("Excellent!")
    print("Done! ")

     

    1. What was the output for each program when examScore variable is set to 85?
    2. Change the examScore values to 95 in each program and run again. What is the output for each program now?
    3. What can you say about the importance of the indentation in a python program using an if statement in Python?

    Python Program 5.4

    # Programmer: Monty Python
    # Date: 1/2/2018
    # Program showing IF/Else statement
    temperature= float(input("Enter a water temperature in degrees Celsius: "))
    if temperature >= 100:
        print("The water is boiling.")
    else:
        print("The water is not boiling.")

     


    10.   Enter and execute the Python program above.

    1. Test the program at least three times. List the three test data points you used and the corresponding output. Be sure you test each part of the condition. Explain why the data you chose were the best data to use to thoroughly test for the program.

    Input 1=

    Output 1=

    Input 2=

    Output 2=

    Input 3=

    Output 3=

    1. Now add print statements to the Python program above so that it prints "It’s turning to steam!" when the water is 100 degrees or hotter, and says "Done!" when the program finishes regardless of what temperature the water is. Rewrite the if/else below with this statement included.


    11.    Consider the following program:

    temperature= float(input("Enter the temperature of H2O at 1 ATM pressure in degrees Celsius: "))
    if temperature == 100:
        print("The water is boiling")
    elif temperature >0 and temperature < 100:
        print("The water is not boiling.")
    elif temperature == 0:
        print("The water could be ice or a mixture of ice and water.")
    elif temperature < 0:
        print("The water has turned to ice")
    else:
        print("you have superheated steam")
    
    1. What new keyword is used in this program?
       
    2. What would the output be if:
      • The water temperature was 100°C
      • The water temperature was 0°C
      • The water temperature was 50°C
      • The water temperature was 100.1°C
         
    3. You can use the elif as many times as you need. Suppose you wanted to add an option that indicated that the water is 37°C and is human body temperature. Where would you add it? What would that code look like?
       
    4. Does the placement of an addition elif clause matter?
       
    5. When is the code associated with the else statement executed?
       
    6. Is the use of the else statement mandatory when creating an if/elif statement? Explain your answer.

    Note

    We can use logical operators to determine logic between conditions (relational expressions).

     

    12.  Sometimes you want to include more than one condition to determine which code segment is executed. You can use the following logical operators to create compound conditions. Examine each operator and a sample of its use and provide an explanation of how the operator works.

    Operator Example Explanation
    and (age >= 17) and (hasLicense = = true)  
    or (cost < 20.00) or (shipping = = 0.00)  
    not not (credits> 120)  


    13.  Assume the value of the variable numBooks is 40.  State the values of each of the Boolean expressions that include a compound condition.

    Expression Boolean Value
    (numBooks > 5) and (numBooks < 100)  
    (numBooks < 5) or (numBooks > 100)  
    not(numBooks * 10  == 100)  


    14.  Suppose you want to determine if a student is ready to graduate. The 3 criteria for graduation are that the student has earned at least 120 credits, their major GPA is at least 2.0 and their general GPA is also at least 2.0.  Which Boolean expression (below the code) would be the correct test for the Python code?

    numCredits = int(input("Enter number of credits:  "))
    majorGPA = float(input("Enter GPA for the major:  "))
    overallGPA = float(input("Enter overall GPA:  "))
    
    if ________:
        print("congratulations?")
        print("You seem to meet all the criteria for graduation.")
    else:
        print("Sorry")
        print("You do not meet all the criteria for graduation/")
    print("Done!")
    

    The Missing Boolean expression is(?)

                a.         numCredits >= 120 or majorGPA >= 2.0 or overallGPA >= 2.0

                b.         numCredits > 120 and majorGPA > 2.0 or overallGPA > 2.0

                c.         numCredits > 119 and majorGPA >= 2.0 and overallGPA >= 2.0

                d.         numCredits >= 120 and majorGPA >= 2.0 and overallGPA >= 2.0

     

    15.  Enter and execute the program in #14. Include your choice for the correct Boolean expression and create several sets of data to test all possibilities for the Boolean expression. List the data you used to test all possibilities for the expression and explain your choices.

    Data Set numCredits majorGPA overallGPA Expression Result (True of False)
    1        
    2        
    3        
    4        
    5        
    6        
    7        
    8        
    9        
    10        

     

    Group Application Questions: Use the Thonny IDE to check your work 


    1. Write a Boolean expression that tests if the value stored in the variable num1 is equal to the value stored in the variable num2.

     

    2. Write a python program that sets a variable called isValid to a Boolean value. Then create an if statement that prints a random number between one and six. If the value stored in the variable isValid equals the Boolean value print true, otherwise print false.
     

    3.  Write the code for an if statement that adds 5 to the variable num1 if the value stored in the variable testA equals 25. Otherwise subtract 5 from num1.
     

    4.  Write a Python program that prompts the user for a word. If the word comes between the words apple and pear alphabetically, print a message that tells the user that the word is valid, otherwise, tell the user the word is out or range.

     

    5.  Write a Python program that prompts the user for a multiple of 5 between 1 and 100.  Print a message telling the user whether the number they entered is valid.

     

    Copyright Statement

    cc4.0
    This work  is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License, this material is a modification by Ehren Bucholtz and Robert Belford of CS-POGIL content, with the original material developed by Lisa Olivieri, which is available here.