Introduction:
The provided Python program is a concise script designed to print odd numbers from 1 to 100. It utilizes a for loop and the range function to iterate through a sequence of numbers, and then selectively prints only the odd numbers from the specified range.
Algorithm:
- Initialize a for loop to iterate through the range of numbers using the range
- Set the starting value as 1, the ending value as 101 (exclusive), and the step value as 2.
- In each iteration of the loop, the current value of num is assigned based on the iteration.
- Print the value of num using the print
- Repeat steps 3-4 for all numbers in the specified range.
Explanation of the Algorithm:
The loop runs through each iteration with the specified range of numbers. In each iteration, the loop variable num takes on the current value from the range. Since the step value is set to 2, only odd numbers will be included in the iteration. As a result, the print function displays the odd numbers from 1 to 99.
The program’s concise design leverages the properties of odd numbers and the range function to achieve the desired outcome efficiently. It serves as a straightforward example of how Python can be used to manipulate and display specific ranges of numbers.
Code :
for num in range(1, 101, 2):
print(num)
Output :
1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
35
37
39
41
43
45
47
49
51
53
55
57
59
61
63
65
67
69
71
73
75
77
79
81
83
85
87
89
91
93
95
97
99
>
Explanation:
In the program, the range function is employed with three arguments: the starting value 1, the ending value 101, and the step value 2. This means that the loop iterates over a sequence of numbers starting from 1 and incrementing by 2 in each step. Since odd numbers are always separated by an interval of 2, this range specification ensures that only odd numbers will be included in the iteration.
Within each iteration of the loop, the current value of num is printed using the print function.