For loop 13 and 14th class

The range() Function in Python

The range() function is a built-in Python function that generates a sequence of numbers. It’s commonly used in for loops to iterate a specific number of times.

Basic Syntax

There are three ways to use range():

  1. range(stop)
  2. range(start, stop)
  3. range(start, stop, step)

1. range(stop) – One Parameter Form

Generates numbers from 0 up to (but not including) the stop value.

python

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

Output:

text

0
1
2
3
4

2. range(start, stop) – Two Parameter Form

Generates numbers from start up to (but not including) stop.

python

for i in range(3, 7):
    print(i)

Output:

text

3
4
5
6

3. range(start, stop, step) – Three Parameter Form

Generates numbers from start to stop, incrementing by step each time.

python

for i in range(0, 10, 2):
    print(i)

Output:

text

0
2
4
6
8

Negative Step

You can count backwards by using a negative step:

python

for i in range(5, 0, -1):
    print(i)

Output:

text

5
4
3
2
1

Important Characteristics

  1. Memory Efficientrange() doesn’t create a list in memory – it generates numbers on demand.
  2. Not Inclusive: The stop value is never included in the sequence.
  3. Immutable Sequence: The sequence produced by range() cannot be modified.

Converting to a List

You can convert a range to a list to see all values:

python

numbers = list(range(1, 6))
print(numbers)  # Output: [1, 2, 3, 4, 5]

Common Use Cases

  1. Looping a specific number of times:

python

for _ in range(3):
    print("Hello!")
  1. Generating indices for sequences:

python

colors = ['red', 'green', 'blue']
for i in range(len(colors)):
    print(i, colors[i])
  1. Creating mathematical sequences:

python

squares = [x**2 for x in range(10)]

Remember that range() creates a sequence of integers, so it’s not suitable for floating-point ranges. For that, you might use NumPy’s arange() or manually increment values in a loop.

For Loops in Python

for loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, set, or string) or other iterable objects. Here’s a basic explanation with simple examples:

Basic Syntax

python

for item in sequence:
    # code to execute for each item

Example 1: Looping through a list

python

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Output:

text

apple
banana
cherry

Example 2: Looping through a string

python

for char in "hello":
    print(char)

Output:

text

h
e
l
l
o

Example 3: Using range() function

python

# Prints numbers 0 to 4
for i in range(5):
    print(i)

Output:

text

0
1
2
3
4

Example 4: Looping with index and value

python

colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
    print(f"Index {index} has color {color}")

Output:

text

Index 0 has color red
Index 1 has color green
Index 2 has color blue

Example 5: Nested for loops

python

for i in range(3):
    for j in range(2):
        print(f"i={i}, j={j}")

Output:

text

i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1

Example 6: Looping with else clause

python

for num in range(3):
    print(num)
else:
    print("Loop completed!")

Output:

text

0
1
2
Loop completed!

Key Points:

  • The for loop executes a block of code for each item in the sequence
  • You can use break to exit the loop early
  • You can use continue to skip to the next iteration
  • The else clause executes after the loop completes normally (not when broken)

Similar Posts

  • Bank Account Class with Minimum Balance

    Challenge Summary: Bank Account Class with Minimum Balance Objective: Create a BankAccount class that automatically assigns account numbers and enforces a minimum balance rule. 1. Custom Exception Class python class MinimumBalanceError(Exception): “””Custom exception for minimum balance violation””” pass 2. BankAccount Class Requirements Properties: Methods: __init__(self, name, initial_balance) deposit(self, amount) withdraw(self, amount) show_details(self) 3. Key Rules: 4. Testing…

  • Built-in Object & Attribute Functions in python

    1. type() Description: Returns the type of an object. python # 1. Basic types print(type(5)) # <class ‘int’> print(type(3.14)) # <class ‘float’> print(type(“hello”)) # <class ‘str’> print(type(True)) # <class ‘bool’> # 2. Collection types print(type([1, 2, 3])) # <class ‘list’> print(type((1, 2, 3))) # <class ‘tuple’> print(type({1, 2, 3})) # <class ‘set’> print(type({“a”: 1})) # <class…

  • Class 10 String Comparison ,Bitwise Operators,Chaining Comparisons

    String Comparison with Relational Operators in Python 💬⚖️ In Python, you can compare strings using relational operators (<, <=, >, >=, ==, !=). These comparisons are based on lexicographical (dictionary) order, which uses the Unicode code points of the characters. 📖 How String Comparison Works 🤔 Examples 💡 Python Important Notes 📌 String comparison is…

  • install Python, idle, Install pycharm

    Step 1: Download Python Step 2: Install Python Windows macOS Linux (Debian/Ubuntu) Open Terminal and run: bash Copy Download sudo apt update && sudo apt install python3 python3-pip For Fedora/CentOS: bash Copy Download sudo dnf install python3 python3-pip Step 3: Verify Installation Open Command Prompt (Windows) or Terminal (macOS/Linux) and run: bash Copy Download python3 –version # Should show…

  • Default Arguments

    Default Arguments in Python Functions Default arguments allow you to specify default values for function parameters. If a value isn’t provided for that parameter when the function is called, Python uses the default value instead. Basic Syntax python def function_name(parameter=default_value): # function body Simple Examples Example 1: Basic Default Argument python def greet(name=”Guest”): print(f”Hello, {name}!”)…

  • Special Sequences in Python

    Special Sequences in Python Regular Expressions – Detailed Explanation Special sequences are escape sequences that represent specific character types or positions in regex patterns. 1. \A – Start of String Anchor Description: Matches only at the absolute start of the string (unaffected by re.MULTILINE flag) Example 1: Match only at absolute beginning python import re text = “Start here\nStart…

Leave a Reply

Your email address will not be published. Required fields are marked *