Write a function that uses iteration to print all numbers from 1 to a given number. For example, if the input is 5, the function should print: 1, 2, 3, 4, 5. Now, extend this function to print only the even numbers within that range. For instance, if the input is 10, the output should be: 2, 4, 6, 8, 10. Finally, modify the function to accept a second argument, which represents the step size. Using iteration, print numbers starting from 1 up to the given number, incrementing by the step size. As an example, given the number 15 and a step size of 3, the expected output is: 1, 4, 7, 10, 13. Be sure to handle edge cases and invalid inputs appropriately.
This document addresses a series of iteration-based coding challenges in Python, progressing from basic printing of numbers to handling step sizes and edge cases.
def print_numbers(n):
"""Prints numbers from 1 to n using iteration."""
if not isinstance(n, int) or n <= 0:
print("Invalid input. Please provide a positive integer.")
return
for i in range(1, n + 1):
print(i, end=" ")
print()
# Example usage
print_numbers(5) # Output: 1 2 3 4 5
This is the straightforward solution, using a simple for
loop to iterate from 1 to n
(inclusive) and printing each number.
n
times.def print_even_numbers(n):
"""Prints even numbers from 1 to n using iteration."""
if not isinstance(n, int) or n <= 0:
print("Invalid input. Please provide a positive integer.")
return
for i in range(2, n + 1, 2):
print(i, end=" ")
print()
# Example usage
print_even_numbers(10) # Output: 2 4 6 8 10
This improved solution starts the loop at 2 and increments by 2, ensuring that only even numbers are printed. This reduces the number of iterations.
n
.def print_numbers_with_step(n, step):
"""Prints numbers from 1 to n with a given step size using iteration."""
if not isinstance(n, int) or n <= 0 or not isinstance(step, int) or step <= 0:
print("Invalid input. Please provide positive integers for n and step.")
return
for i in range(1, n + 1, step):
print(i, end=" ")
print()
# Example usage
print_numbers_with_step(15, 3) # Output: 1 4 7 10 13
This function introduces a step size to the iteration. It checks for invalid inputs for both n
and step
to ensure they are positive integers.
n
and step
.n
, it will still execute correctly, printing only the starting number (1).These examples illustrate how iteration can be used to solve simple numerical problems with increasing complexity. Each function includes input validation and considers potential edge cases to ensure robustness.