Course Hero Logo

Python Part 5 -- Loops-3.pptx - Loops: The while Loop • A...

Course Hero uses AI to attempt to automatically extract content from documents to surface to you and others so you can study better, e.g., in search results, to enrich docs, and more. This preview shows page 1 - 7 out of 20 pages.

Loops: The whileLoopA loop is an iterationstructureLines of code are executed repeatedly until a condition is metHere's a loop which executes until the user enters 'y' or 'Y':choice = "y"# "seed" the loopwhilechoice.lower() == "y":print("Hello!")choice = input("Say Hello again? (y/n): ")print("Bye!")1
choice = "y"# "seed" the loopwhilechoice.lower() == "y":print("Hello!")choice = input("Say Hello again? (y/n): ")print("Bye!")The indented code runs until the condition is false(which happens when choice.lower() is not "y")This means that if we didn't "seed" the value of choice as "y", the loopmay not run at all! This is known as a pre-testloop:The condition is evaluated before the loop statements are executedprint("Bye!") is not part of the loop structure, it will execute whetherthe condition is true or not“y” is known as a sentinelvalue: input is read until the sentinel isentered2
Write a program which prints the numbers 0through 4 to the console using a loopUse a variable named "counter"Use a compound assignment operator toincrement the variable30 1 2 3 4The loophas ended.
#!/usr/bin/env python3# counter.py#counter = 0while counter < 5:print(counter, end=" ")counter += 1print("\nThe loophas ended.")4
Infinite LoopsIf a loop condition is never met, a loop can run“forever”This is known as an infiniteloopInfinite loops are frequently the result of programmingerrorswhile True:# any statements here will run forever5
The forLoopA for loop runs once for each integer in a collectionof integersThe range() function produces the collection of integersfor i in range(5):print(i, end=" ")print("\nThe loop has ended.")The for loop in Python is also known as a collection-controlledloop(also known as a "count-controlled loop")60 1 2 3 4The loop has ended.

Upload your study docs or become a

Course Hero member to access this document

Upload your study docs or become a

Course Hero member to access this document

End of preview. Want to read all 20 pages?

Upload your study docs or become a

Course Hero member to access this document

Term
Fall
Professor
N/A
Tags

Newly uploaded documents

Show More

Newly uploaded documents

Show More

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture