Reputation: 1
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?
Upvotes: -1
Views: 1057
Reputation: 1
(there is also a alternative if you tell the script to print out the numbers adding by 1 it will tell you 158729 then stop) script below↓↓↓
i = 1 while i < 9999999999: print(i) i += 1
if that is what you meant by biggest number even though this one just makes the script end at that but this may also be on the version or type of python program you run it on
Upvotes: 0
Reputation: 260
print
the number after the while
loop is finished.
n=1
bigNumber = 0
while n <= 10:
bigNumber = n
n = n*2
print(bigNumber)
Upvotes: 0
Reputation: 3
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
Upvotes: 0
Reputation: 385
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.
Upvotes: 0