Python Outputs All Odd Numbers from 1 to n
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)
for i in range(1, n + 1):
if i % 2 != 0:
print(i)
Code Explanation:
n = int(input("请输入一个正整数 n: ")): Get a positive integer n from user input.for i in range(1, n + 1):: Usefora loop to iterate through 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 equal to 0, then i is odd.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 9Other Extensions
Python3 Examples