loader image
Skip to main content
If you continue browsing this website, you agree to our policies:
x

Topic outline

  • Unit 3: Input and Flow Control Statements

    If you have mastered the previous units, you now have the ability to put together a series of sequential Python instructions capable of performing some basic calculations. You also have the ability to format those results and output them to the screen. This unit covers "program flow control", which is necessary for programs to make decisions based upon a set of logical conditions. Your knowledge of relational and logical operators will be pivotal for applying a new set of Python commands that will enable you to control your program's flow. We will also introduce the "input" command so that the keyboard can be used to input data into a program.

    Completing this unit should take you approximately 4 hours.

    • Upon successful completion of this unit, you will be able to:

      • explain the differences between programmer-initialized variables and user input variables;
      • write a program that will take string and numerical data from the keyboard;
      • write conditional statements using logical operators;
      • write for loops and while loops using logical operators and the range function for flow control; and
      • explain how break, continue, and pass statements are used in loops.
    • 3.1: Reading Data from the Keyboard

      • The input command is necessary when we want to obtain input from a keyboard. So far, variables have been initialized or assigned values within a given Python script, with commands such as:

        a=3
        b=27
        c=a+b

        It is often the case that a program requires keyboard input from the user to perform its function. This is exactly what the 'input' command is for. This instruction can output a message, and the program will wait for the user to input a value. Try running this command in the Repl.it run window:

        city=input('Enter the name of the city where you are located: ')
        print(city)

        You should be aware that the input function returns data of type str (that is, string data). If numerical data is required, an extra step must be taken to perform a type conversion using either the int or float commands. Copy and paste this set of commands into the run window and then run code using an input value of 34 when prompted for user input:

        temperature_str=input('Enter the temperature: ')
        print(temperature_str)
        print(type(temperature_str))
        print()
        temperature_int=int(input('Enter the temperature: '))
        print(temperature_int)
        print(type(temperature_int))
        print()
        temperature_float=float(input('Enter the temperature: '))
        print(temperature_float)
        print(type(temperature_float))
        print()

        The variable names have been chosen to emphasize and distinguish between their data types. The input command offers the convenience of creating user-defined values within a program. At the same time, it is important to make sure the input value's data type matches the intended use of the variable.

    • 3.2: Using Conditional Statements

      • Conditional statements are necessary for a program to make decisions based upon a set of logical conditions. There are three main constructs in Python for this: the if statement, if-else statements, and the if-elif statement. 

        In Repl.it, run this block of code that checks a logical condition based upon the value of an input variable:

        avalue= int(input('Enter an integer greater than 10: '))
        if avalue>10:
            print('Thank you')
            avalue=avalue/2
            print('This is your value divided by 2: ', avalue)
        print('Did your if code execute?')
         

        Try running the code first for an input value of 14 and then run it again for an input value of 5. The if statement checks the relational condition '>' to see if the variable avalue is greater than 10. If so, the indented code will be executed. If not, the program will not execute the indented code.

        Notice the syntax required for the if statement to work:

        • The logical expression following the "if" must end with a colon (:) 
        • The code to be executed if the logical condition is true must be indented. Indentation is how Python knows you have a group of commands inside the if statement 
        • Indentation can be accomplished in Repl.it using the "tab" key. In the Repl.it editor, this is equivalent to typing two spaces. Some Python editors prefer four spaces for indentation. 

        This flowchart illustrates how the if statement works: 

        how if statement works

        When the if statement is encountered, if the conditional expression is true, then the indented group will be executed. Otherwise, the program will jump over the indented group and not execute those commands. In other words, it is possible to have code in a program that never executes because a logical condition has not been satisfied. It should now be clear why if statements are called "program control" statements: they control the logical flow of the program.

        Next, we have the if-else statement, which allows for groups of code to be introduced for both the true and the false condition. Run this code snippet in Repl.it a few times using different values for the input:

        avalue= int(input('Enter an integer greater than 10: '))
        if avalue>10:
            print('Thank you')
            avalue=avalue/2
            print('This is your value divided by 2: ', avalue)
        else:
            avalue=avalue/5
            print('This is your value divided by 5: ', avalue)
            print('Which code group executed?')

        You should notice different program outputs depending on the logical expression. Again, notice the indentation and notice both the "if" and "else" statements must be terminated with a colon (:). This flowchart illustrates how the if-else statement works:

         

        .

        Finally, the if-elif statement allows for several logical conditions to be checked. Run this code snippet in Repl.it a few times using different values for the input:

        avalue= int(input('Enter an integer greater than 10: '))
        if avalue>=10:
            print('Thank you')
            avalue=avalue/2
            print('This is your value divided by 2: ', avalue)
        elif (avalue<10) and (avalue>4):
            avalue=avalue/5
            print('This is your value divided by 5: ', avalue)
        else:
            avalue=avalue*100
            print('This is your value times 100: ', avalue)
        print('Which code group executed?')

        Notice, once again, the indentation and the colon that are necessary to make the if-elif work execute properly. Also, observe how a series of conditions using logical and relational operators are checked to control which group of code will execute. This flowchart illustrates how the if-elif statement works:

        .

        The if-elif construct allows for several logical conditions to be checked using relational and logical operators. Understanding how to use if, else, and elif statements is central to becoming a seasoned programmer. Make sure to practice the examples you see here in Repl.it.

      • Read this for more on conditional statements.

    • 3.3: Loop and Iterations

      • Loops are necessary when we need to perform a set of operations several times. The first type of loop we will discuss is called the while loop. The while loop checks a logical condition like the if statement. If the condition is true, the code inside the while loop will execute until the condition being checked becomes false. Run this code in Repl.it:

        avalue= int(input('Please enter the number 10: '))
        while (avalue != 10):
            print('Your input value is not equal to 10')
            print('Please try again: ')
            avalue= int(input('Enter the number 10: '))
        print('Thank you')
        print('You entered a value of 10')

        This while loop checks to see if the value input was equal to 10. If not, the while loop will continue to execute the indented code until a value of 10 is input. The syntax rules are similar to those of the if statements:

        • The logical expression following the "while" must end with a colon (:) 
        • The code to be executed if the logical condition is satisfied must be indented. 
        • Indentation is how Python knows you have a group of commands inside the while statement Indentation can be accomplished in Repl.it using the "tab" key. In the Repl.it editor, this is equivalent to typing two spaces. Some Python editors prefer four spaces for indentation. 

        Make sure you run the examples provided in Repl.it. When we execute the code within a loop over and over again, the process is known as iteration.

      • The for loop is useful when we know how many times a loop is to be executed. Rather than basing the number of iterations on a logical condition, the for loop controls the number of times a loop will iterate by counting or stepping through a series of values. Run this snippet of code in Repl.it:

        for i in range(5):
            print(i)

        The range(5) command creates a series of five values from 0 to 4 for the variable i to cycle through. The statement for i in range(5) effectively means use the variable i to count through five values starting at 0 and stopping at 4 (Python, by design, begins counting with the value 0). Also, once again, pay close attention to the placement of the colon (:) at the end of the for statement as well as the indentation. The syntax rules should look very familiar at this point. They are exactly the same as for if statements and while loops.

        Consider this next snippet of code:

        n=8
        sumval=0;
        for i in range(n):
            sumval = sumval+i
            print('Adding ', i,'to the previous sum = ',sumval)

        This loop counts from 0 to n-1, where n has been set to a value of 8. An initial sum is set to zero and then successive values of the variable i are added to the sum each time an iteration of the loop takes place. In other words, the loop counter variable i can be used within the loop as it is being updated. As will we see, the loop variable is often used as part of some computation within the loop. Here is an example of how powerful Python can be when using a for loop to cycle through a series of values.

        strval='forever'
        e_count=0
        for letter in strval:
            if letter =='e':
                e_count = e_count + 1
        print('The letter e occurred ', e_count, 'times')

        Notice how the "if" statement is "nested" (and, therefore, indented) within the "for" loop. The variable letter cycles through each character in the string strval, which has been initialized to the string forever. If an "e" is found while iterating through each character, the count variable is incremented. When the loop is finished, the number of occurrences is output to the screen.

        It is also possible to nest loops within loops. We will discuss more of these types of loops as we go deeper into the course. For now, run this code in Repl.it:

        m=4
        n=3
        for i in range(m):
            for j in range(n):
                print('i=',i,' j=',j)

        This is called a nested "for" loop because the inner "for" loop depending on the variable j is nested within the outer "for" loop, which depends on the variable i. This should be clear from the indentation of the inner loop with respect to the outer loop. For each iteration of the variable i, the variable j cycles through all of its possible values which depend upon range(m). In order for ito be updated to its next value, the inner loop must iterate through all of its values. Make sure you can relate the program output shown the screen to how the nested loop iterates through its values.

        After you watch the video and test the examples in Repl.it, revisit the file in the "while" loop section and read through the section on "for" loops. Make sure to practice the for loop examples in Repl.it.

      • Sometimes it is necessary to exit a loop abruptly when a certain condition is met. The "break" statement is sometimes useful for such an application. Consider this code:

        strval='forever'
        for letter in strval:
            if letter =='e':
                break
        print('The letter e has been found')

        In this case, the break statement terminates the loop if the character e is found in the strval string.

        On the other hand, encountering a given condition within a loop may require skipping over a set of commands and effectively "fast-forward" to the next iteration. The "continue" statement is useful for these applications.

        Finally, the "pass" statement within a loop is a null statement that does nothing. It is sometimes useful when placed in a program where code is intended but has not yet been written. Read this page and practice the examples.

    • 3.4: Further Study

      • Here are some supplementary videos that you can review if you'd like a bit more practice the concepts in this unit.

    • Study Session Video Review

    • Unit 3 Review and Assessment

      • In this video, course designer Eric Sakk walks through the major topics we covered in Unit 3. As you watch, work through the exercises to try them out yourself.

      • Take this assessment to see how well you understood this unit.

        • This assessment does not count towards your grade. It is just for practice!
        • You will see the correct answers when you submit your answers. Use this to help you study for the final exam!
        • You can take this assessment as many times as you want, whenever you want.