Bill
Bill

Reputation: 331

how to make a while statement run one more time in python 3

Is there any way to make a while statement run one more time after it has finished?

This will obviously print 'hello world' 31 times. Though in longer programms it is kinda stupid to re-write the whole code again after the loop.

Any help will be appreciated!

UPDATE! The reason i didnt do x<31 is the following .

I am building a blackjack game.So, when the bank reaches 30$ another round is being played and then the game is over.

bank's value depend's on players betting (bank strats with 10$ , if player bets 3 and loses the round the bank has 13$)

Upvotes: 3

Views: 10518

Answers (3)

Ehsan
Ehsan

Reputation: 1

I my self prefer else statement with while loop to do it one more time as an example check this out :

oncemore = True 
num_list = []
while oncemore:
    num_list.append((num % 10))
    num = int(num / 10)
    if int((num/10)) == 0:
        oncemore = False
else:
    num_list.append((num % 10))
    num = int(num / 10)
    num_list.reverse()
    return num_list

after my while loop completely finished else statement do what ever i want one more time just keep this point in your mind while loop should completely finish without any break

Upvotes: 0

jgritty
jgritty

Reputation: 11925

After further editing of the question, this is a fairly straight forward way to do what you want.

EDIT:

done = False
x = 1
while not done:
    if x >= 30:
        done = True  # Set done to true once x is greater than or equal to 30
                     # then print one last time
    print('hello world')
    x+=1
    print(x)

Instead of this:

x = 1
while x < 30:
    print('hello world')
    x += 1
    print(x)
print('hello world')

Upvotes: 0

tobias_k
tobias_k

Reputation: 82899

Of course, if your condition is numeric, like x < 30, you could just change it to x < 31 or x <= 30, but this may not always be possible. Another method would be to wrap the loop body into a function, and call it within and once more after the loop, but this, too, might not always be practical.

Alternatively, you could use a disjunction of the original condition and some expression that evaluates to True the first time, and then to False.For example, you could use an iterator on the list [True, False]. As long as the actual condition is True, that second part is not evaluated at all (or is lazy), then, when the condition is False, next is called, yielding True the first time and then False

x=1
oncemore = iter([True, False])
while x < 30 or next(oncemore):
    x+=1
    print(x)

Or you could defer checking the condition to inside the loop. This way, the exit condition will only take effect in the next iteration of the loop.

once_more = True
while once_more:
    if not (x < 30):
        once_more = False
    # original loop body here

Upvotes: 8

Related Questions