Input-Controlled Loops

tags: #python/documentation/python_loops

Input-controlled loops are a type of loop in programming where the number of iterations is determined by user input. These loops continue to execute as long as a certain condition, often based on user input, remains true. Input-controlled loops are commonly implemented using while loops, where the loop condition is based on user-provided input.

Example:

# Input-controlled loop
while True:
    user_input = input("Enter a number (type 'exit' to end): ")

    if user_input.lower() == 'exit':
        print("Exiting the loop.")
        break  # Exit the loop if the user enters 'exit'
    
    # Process the user input (you can add more logic here)
    try:
        number = int(user_input)
        square = number ** 2
        print(f"The square of {number} is {square}")
    except ValueError:
        print("Invalid input. Please enter a valid number.")
Powered by Forestry.md