Python Outputs All Odd Numbers from 1 to n

Document 对象参考手册Python3 Examples

Write a Python program to output 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 Explanation:

  1. n = int(input("请输入一个正整数 n: ")): Get a positive integer n from user input.
  2. for i in range(1, n + 1):: Usefora loop to iterate through 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 equal to 0, then i is odd.
  4. print(i): If i is odd, print that number.

Output Result: Assuming the user enters n as 10, the program will output:

1
3
5
7
9

Document 对象参考手册Python3 Examples

Other Extensions