Le Lee
Le Lee

Reputation: 15

while loop still loops one more time even though condition is false

My code seems to be stuck in this while loop forever:

array = []
b = 1
while b != 0:
    b = int(input("please enter whole numbers "))
    array += [b]
print (array)     

The meaning of the code is to put user inputs into an array and stop when user enter 0. I don't know why the loop manages to continue the code even though the condition is false. I thought as long as condition is false, python will stop right there!

I keep getting 0 as an element in the array when I don't want it to be in.

Upvotes: 1

Views: 2021

Answers (3)

magamongo
magamongo

Reputation: 31

"break" helps you to do that.

array=[1]
while array[-1] != 0:
  b = int(input("please enter a whole number"))
  array += [b]
  if array[-1] == 0:
    print(array[1:-1])
    break

Hope this helps :)

Upvotes: 0

JLD
JLD

Reputation: 89

I have modified magamongo's answer a little in order to not use break, but you could also use it as in quamrana's answer:

array = []
b = 1
while b != 0:
    b = int(input("please enter whole numbers "))
    array += [b]
array = array[:-1]
print(array)

Upvotes: 1

quamrana
quamrana

Reputation: 39404

I think you could use your own exit condition and not rely on the while statement itself stopping:

array = []

while True:   # never exit here
    b = int(input("please enter whole numbers "))
    if b == 0:
        break    # exit the loop here
    array += [b]
print (array)   

Upvotes: 0

Related Questions