JazzBLues
JazzBLues

Reputation: 11

Negative and positive Odd numbers using for loop in python

I'm new here at this site, so please acknowledge me if I done anything wrong. Anyways, I'm trying to write a simple program that generates all odds numbers from 1 to n using for loop or while loop.

n = int(20)

for number in range(1, n + 1):
    if(number % 2 != 0):
        print(format(number), end=" ")

But the code above prints only the positive odd numbers. If I change the value of n into a negative number, there is no output. I forgot how to write the code that if n is an even number, the largest generated odd number is n-1. Sorry for my bad English. Thank you guys for the help.

Upvotes: 1

Views: 738

Answers (1)

theunknownSAI
theunknownSAI

Reputation: 330

range takes three parameters start, end, increment

start end increment output
positive positive positive Yes
positive positive negative No
positive negative positive No
positive negative negative Yes
negative positive positive Yes
negative positive negative No
negative negative positive No
negative negative negative Yes
n = -int(20)
sign = 1 if n > 0 else -1
for number in range(sign, n + sign, sign):
    if (number % 2 != 0):
        print(format(number), end=" ")

Make these changes in the code and it will work for negative and positive numbers.

Upvotes: 1

Related Questions