Home > OS >  Finding the biggest number for a sequence given by the while loop
Finding the biggest number for a sequence given by the while loop

Time:09-28

I'm currently learning Python, more specifically, how the loop while works. As far as I know, this loop can be used to create sequences of numbers with and specific condition. For example,

n=1

while n < 10:
    n = n*2
    print(n)

Which gives the powers of two up to 16:

2
4
8
16

But I was wondering if there's a way for the loop to print only the biggest number of the sequence, in this case, it would be 16. Here's my attempt,

n=1
bigNumber = 0
while n <= 10:
    bigNumber = n
    n = n*2
    if n < bigNumber:
        print(bigNumber)

However it doesn't work. Could someone point out were the mistake is?

CodePudding user response:

Your code doesn't work as intended because the condition of the if statement is never fulfilled. Just take for example n=4. Then in the loop you first assign bigNumber = 4 and then n is increased to 8. And at this point, always n > bigNumber.

The easiest way here to get the correct answer is to print n after the loop (already mentioned in a comment) as n is always incrementing.

CodePudding user response:

You can do this in 2 ways.

If you just want to print the final value you can just ommit part of the code:

n=1

while n < 10:
    n = n*2

print(n)

If you want to keep all values and then show the highest one:

n=1
num_list = []

while n < 10:
    num_list.append(n)
    n = n*2

print(f'From the numbers {num_list} the highest is {max(num_list)}')

The max() function is built to find the highest value in a list.

The output should be:

From the numbers [1, 2, 4, 8] the highest is 8
  • Related