def print_even_numbers():
"""This function prints all even numbers from 1 to 20."""
for num in range(2, 21, 2):
print(num, end=" ")
print_even_numbers()
#source code --> clcoding.com
Code Explanation:
Function Definition
def print_even_numbers():
def is used to define the function.
print_even_numbers is the function name.
It does not take any parameters, since the range is fixed (1 to 20).
Docstring (Optional but Recommended)
"""This function prints all even numbers from 1 to 20."""
Describes what the function does.
Helps in documentation and debugging.
Using the range() Function
for num in range(2, 21, 2):
range(start, stop, step) generates a sequence of numbers:
2 → Start from 2 (first even number).
21 → Stop before 21 (last number is 20).
2 → Step by 2 (only even numbers).
The loop runs:
2, 4, 6, 8, 10, 12, 14, 16, 18, 20
Printing the Numbers
print(num, end=" ")
Prints each number on the same line with a space (end=" ").
Output:
2 4 6 8 10 12 14 16 18 20
Calling the Function
print_even_numbers()
Calls the function, and it prints:
2 4 6 8 10 12 14 16 18 20
0 Comments:
Post a Comment