🔄

Understanding Loops and Range in Python

Sep 18, 2024

Notes on Loops in Python

Introduction to Loops

  • Loops are used to repeat tasks multiple times.
  • Example: Sending a message to a user and retrying if it fails.

For Loop Structure

  • Basic Syntax: for number in range(3): # Code to repeat
  • range(n) generates numbers from 0 to n-1.
  • Indentation is crucial in Python to define blocks of code.

Using range() Function

  • range() takes up to three arguments:
    1. start: Starting number (default is 0).
    2. stop: End number (exclusive).
    3. step: Increment (default is 1).
  • Example: for number in range(1, 4): print(number)
    • Output: 1, 2, 3
  • Multiplying Strings:
    • String multiplied by a number repeats the string.

Breaking Out of Loops

  • Use the break statement to exit a loop.
  • Example: if successful: break

Handling Failed Attempts

  • Use an else statement with a loop to handle cases where the loop did not break.
  • Example: else: print('Attempted 3 times and failed')

Nested Loops

  • A loop inside another loop (outer loop and inner loop).
  • Example: for x in range(5): for y in range(3): print(f'({x}, {y})')
  • Output: Coordinates (0,0), (0,1), ..., (4,2).

Understanding range() Function

  • Returns a range object which is iterable.
  • Can be used in a for loop or with other iterable types (like strings and lists).

Exercise: Display Even Numbers

  1. Write a program to display even numbers from 1 to 10.
  2. Use range(1, 10).
  3. Check if a number is even using modulus operator:
if number % 2 == 0: print(number)
  1. Count the even numbers with a separate variable.

Conclusion

  • Summary of key points on loops and the range() function.
  • Encourage further learning with additional resources.