123k views
0 votes
Write a program that prints all the positive odd numbers less than n. In addition, the program will make every other odd number negative. For example, if n=20 then the program will print the numbers 1,−3,5,−7,9,−11,13,−15,17,−19.

User Orange
by
7.9k points

1 Answer

6 votes

Here's a Python program that accomplishes the task you described:

def print_odd_numbers(n):

odd_numbers = [i for i in range(1, n) if i % 2 != 0] # Generate a list of all positive odd numbers less than n

for i in range(len(odd_numbers)):

if i % 2 == 1: # Make every other odd number negative

odd_numbers[i] *= -1

for number in odd_numbers:

print(number)

n = 20

print_odd_numbers(n)

When you run this program with n = 20, it will generate a list of all positive odd numbers less than 20, which is [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]. Then, it will make every other odd number negative, resulting in [1, -3, 5, -7, 9, -11, 13, -15, 17, -19]. Finally, it will print each number on a separate line.

User Dylan Corriveau
by
7.5k points

No related questions found