PYTHON TUTORIALS

Python Tutorials: Loops

[Enter image here]

When making changes to Data Structures, it can be tedious to make changes to individual elements when there could be tens or hundreds of elements. Loops provide a way to iterate over each element in a data structure, or perform an action until a condition has been met, to efficiently apply necessary changes. This tutorial will cover the following learning objectives:

  • What For Loops Are and When to Use Them
  • What While Loops Are and When to Use Them
  • What Loop Control Statements Are and When to Use Them

What For Loops Are and When to Use Them




Summary

  • A For Loop will execute a block of code a fixed number of times. You can iterate over a range of values, a string, or elements in a data structure. To create a For Loop, use the following syntax:
    for [iterator] in [iterable]:
       [perform action on iterator]
  • The Range function is used to define a sequence of numbers between a minimum and maximum. To use this in a For Loop, use the following syntax:
    for [iterator] in range([min_number], [max_number]):
       [perform action on iterator]
  • If you want to reverse the range of numbers defined in the Range function, use the Reversed Function. This is used with the following syntax:
    for [iterator] in reversed(range([min_number], [max_number])):
       [perform action on iterator]
  • If you want to change the steps associated with a defined sequence of numbers, use the Step argument of the Range Function. This is used the following syntax:
    for [iterator] in range([min_number], [max_number], [step_count]):
       [perform action on iterator]
  • When iterating over a string, the loop will iterate over each character in the string. Example
    for characeter in "My Name is Henry":
       print(character)
  • NOTE: When defining the maximum number in the Range function, always add one to the maximum number you wan to exclude since the function is "exclusive", meaning it excludes the maximum number as defined, by default.

What While Loops Are and When to Use Them




Summary:

  • A While Loop will execute a block of code WHILE a condition remains TRUE. TO create a While Loop, use the following syntax:
    while [condition]:
       [perform an action]
  • The Input function is used to make your Python script interaction in the Terminal/Console. THis is helpful for when you want to test your code against some test inputs. This function is used with the following syntax:
    input("[string]: ")
    Console: "[string]": [user inputs STRNG here]
  • If you want to prompt the user to enter an Integer, use the Int function as discussed in the Data Types Tutorial in conjunction with the Input function. Example:
    int(input("[string]: "))
    Console: "[string]": [user inputs INTEGER here]
  • An Infinite Loop is created when you specify a condition that will ALWAYS be true (e.g., 1==1, 2>1, True==True). Example:
    while 1==1:
       [perform an action]
  • NOTE: The only time you should use an Infinite Loop is when you want an action to take place the entire time your application or script is running.

What Loop Control Statements Are and When to Use Them




Summary:

  • A Loop Control Statement is used to change a loop's execution cycle from its normal sequence.
  • The Break Control Statement is used to terminate the loop entirely if a specific condition is met. This Control Statement is very useful for breaking out of Infinite Loops. Example:
    while True:
       food = input("What is your favorite food? ")
       if food != "":
          break
  • The Continue Control Statement is used to skip to the next iteration of the loop. This is useful for when you want your loop to skip over erroneous data. Example:
    ages = [22, 35, -10, 195, 55]
    for age in ages:
       if age < 0 or age > 100:
          continue
       else:
         print("Age is valid")
  • The Pass Control Statement is used as a placeholder until an action is placed. This is useful for when your still building the logic of your application or script. Example:
    while user_input > 30:
       pass
  • NOTE: You should use a set rather than a list if you want to check if a specific value is in a range of values (whether strings or numeric values).

Exercise

Congratulations! You just completed the Loops Tutorial! To help test your knowledge, let's practice creating some Loops.
**It's highly recommended that you complete the exercise outlined in the previous tutorial before beginning this exercise.**

Instructions:

  1. Open your IDE (e.g., VS Code, PyCharm, Spyder).
  2. Create a New Python File. Name it "loops.py"
  3. In the Newly Created Python File, complete the following tasks:
    1. Declare a variable named "names" and give it the following elements: "Josh", "Samuel", "Arnold", "Leonard", "Tabitha".
    2. Create a For Loop that prints out each element in the "name" variable.
    3. Add the following element to "names": 45. Create a For Loop that prints out each element in "names" if the element is NOT equal to 45. Otherwise print out "That name is not valid."
    4. Declare an integer input variable named "age_input" that allows the user to input their age.
    5. Create an infinite While Loop that ensure the user's input is less than 100 and greater than 0. If the user input a valid value, break the loop.
    6. The element "Tabitha" in the "names" variable was inputed by mistake. Create a For Loop that prints out each element in the "name" variable, unless the element equals "Tabitha", then skip the value.
    7. Create a While Loop that states whether or not the user's age is equal to 21. Put a placehodler for the loop's logic.
  4. Exercise Completed! Click here to view the answers.
  5. Have any issues with the above exercise? Post your question on Discord!