Python Output All Odd Numbers from 1 to n
Write a Python program that outputs all odd numbers from 1 to n. Assume n is a positive integer.
Example
n
=
int
(
input
(
"Please enter a positive integer n: "
)
)
for
i
in
range
(
1
,
n +
1
)
:
if
i %
2
!=
0
:
(
i
)
Code analysis:
n = int(input("请输入一个正整数 n: ")): Get a positive integer n from the user's input.for i in range(1, n + 1):: When usingforThe loop iterates over all integers from 1 to n.if i % 2 != 0:: Check whether the current integer i is odd. If the remainder of i divided by 2 is not 0, then i is odd.print(i): If i is odd, print the number.
Output: assuming the user enters n = 10, the program prints:
1
3
5
7
9
Python3 Examples