Chapter 7a - While Loop
While Loopsβ
While Loop
The BooleanExpression is tested, and if it is true, the Statement is executed. Then, the BooleanExpression is tested again. If it is true, the Statement is executed. This cycle repeats until the BooleanExpression is false.
Print Program Untill I tell you to stopβ
- Prints ``
continueProgram="y"
while (continueProgram == "y"):
print("Hello!")
continueProgram = input("Continue program? y/n").lower()[0]
print("Program Terminated")
π§ͺ Try the code out!
Reusable Adderβ
The following program adds 2 numbers until the user tells it to stop
programFinished="yes"
while (programFinished == "yes"):
n1 = int(input("Enter number 1"))
n2 = int(input("Enter number 2"))
print(n1+n2)
programFinished = input("Enter Yes if you want to continue using the calculator or No otherwise").lower()
π§ͺ Try the code out!
Exerciseβ
These are used when we just want them to play around with the code first.
Practice
- Create a program that prints your name in two lines until you type
n - Use the following Canvas
πββοΈ Example of an the expected Program