Introducing the While Loop: Python Code for “99 Bottles Of Beer On The Wall”

Coding can be oddly weird and fun? Or terrible. Your choice.

Lucy Dan 蛋小姐 (she/her/她)
eggsisting

--

Photo by Pradnyal Gandhi on Unsplash

A while loop is a cool programming thing where as long as a condition is met, the things you write within the loop will continue happening.

For example, while we’re counting down from 99 bottles of beer in the classic sea shanty with the following lyrics:

99 bottles of beer on the wall, 99 bottles of beer.
Take one down, pass it around, 98 bottles of beer on the wall…

98 bottles of beer on the wall, 98 bottles of beer.
Take one down, pass it around, 97 bottles of beer on the wall…

We can start off by defining that we begin with 99 bottles (num_bottles).

Within our while loop, as long as we have more than 0 bottles, we want to continue singing our lyrics.

The str() function helps convert a numerical value into a string (word) value that can be stitched together with the rest of the lyrics using “+”.

The print() function makes sure that our program prints (or sings?) the lyrics out to us.

Finally, before wrapping up the loop, we have to remove a bottle of beer by resetting our num_bottles to account for the lost…

--

--

Lucy Dan 蛋小姐 (she/her/她)
eggsisting

Filling in the cracks on conflicting self improvement advice and translating how these can work for a more diverse audience ✨ Icon by: @jkbarts #WEOC writer.