Python Problem Solved
Python Range() Function Simulator
Your task in this Python problem is to create a Python function that works like the popular range() function.
Write a Python function that returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.
Steps
- Define the function: Create a function named “generate_sequence” that takes the following parameters with default values:
- start (default value: 0)
- step (default value: 1)
- stop (no default value, as it needs to be specified)
- Implement the logic: Use a while loop to generate the sequence by starting from the “start” value and incrementing by the “step” value until it reaches the “stop” value.
- Return the sequence: Store the generated sequence in a list and return the list as the output of the function.
For more Python practice visit our real-life Python practice projects.
Python Problem Solved
def generate_sequence(stop, start=0, step=1):
sequence = []
while start < stop:
sequence.append(start)
start += step
return sequence
Expected output
generate_sequence(15)
## Ouput
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]