How to write the program that prints out all the positive integer values from 1 up to the input number and each pair of numbers is flipped?

Question:

My code almost works:

number = int(input("Please type in a number: "))
 
a = 2
b = 1
 
while a in range(number) or b in range(number):
    print(a)
    print(b)
    a += 2
    b += 2

with input 6 it works as it should:

Please type in a number: 6
2
1
4
3
6
5

but with input 5 it doesn’t and show the sequence 2 1 4 3 instead 2 1 4 3 5

Asked By: Denis

||

Answers:

you can do this with he help of the range function. Here is a simplified version:

acc = []
for i in range(1, number, 2):
    acc.append(i+1)
    acc.append(i)
if number % 2:  # if your number is odd then add the last number manually
    acc.append(number)
Answered By: Nullman

In the for loop, we are iterating over all the odd numbers up to n (1, 3, 5 …) and printing the pair of consecutive numbers ( i+1 – even no. first ). As we only wanted numbers up to n to print, we’re checking if i+1 is less than or equal to n (p.s. inside for loop the value of i is always less than or equal to n so we just needed to make sure if i+1 matches that condition too ).

n = int(input())
for i in range(1, n+1, 2):
    if i+1 <= n:
        print(i+1)
    print(i)
Answered By: Nick

It looks like you were very close the way you wrote it, but you didn’t add the print function at the end so you were looking at the wrong values as output. Also, use "and" instead of "or" in this case.

number = int(input("Please type in a number: "))

a = 2
b = 1

while a in range(number) and b in range(number):
    print("Original a", a)
    print("Original b", b)
    a += 2
    print("Current a", a)
    b += 2
    print("Current b", b)
Answered By: bethis
number = int(input("Please type in a number: "))        
a = 2       
b = 1         
count = 1       
while count <= number:
       
    count += 1
    if a <= number:
        print(a)
        a += 2
    if b <= number:
        print(b)
        b += 2
Answered By: Remy-boi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.