Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Output All Odd Numbers from 1 to n

Python Output All Odd Numbers from 1 to n

Document Object Reference Manual Python3 Examples

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

:

       

print

(

i

)

Code analysis:

  1. n = int(input("请输入一个正整数 n: ")): Get a positive integer n from the user's input.
  2. for i in range(1, n + 1):: When using for The loop iterates over all integers from 1 to n.
  3. 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.
  4. print(i): If i is odd, print the number.

Output: assuming the user enters n = 10, the program prints:

1
3
5
7
9

Document Object Reference Manual Python3 Examples