Print Odd Numbers in Python (Handling Negatives)
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
This code defines a function named print_odd_numbers that prints odd numbers within a specific range. If the input number (n) is positive, it prints odd numbers from 1 to n in ascending order. If the input is negative, it prints odd numbers from n to -1 in ascending order (from the most negative to -1).
How to use:
- The program takes a number from the user.
- The function
print_odd_numbersis called with that number. - The output is displayed as odd numbers on a single line, separated by spaces.
Example: If the input is 7, the output is 1 3 5 7. If the input is -7, the output is -7 -5 -3 -1.
This code is useful for teaching loops, conditions, and handling negative numbers in Python.