Python Lps

What is a Loop?

Automates repetitive tasks

  • Loops allows you to do the same action(s) on every item in a list
  • Two types of loops in Python:

For Loop

Iterates/traverses over a sequence (list, tuple, string)

each item in sequence

Last item reached?

Y/N

Back to sequence

Yes

No

Exit Loop

For Loop

  • Used to run your code a specific number of times
  • For loops starts with the keyword for
  • A variable follows the keyword for that takes the value of the item inside the sequence on each iteration
  • The body of the for loop is indented

For Loop

Looping through items in a tuple

Looping through characters in a string

Generate a series of numbers

range ( ) function

  • The range ( ) function generates a series of numbers
  • Example 1 prints numbers from 0 through 10
  • Example 2 prints numbers from 1 through 10
  • The output will never contain the end value

List of Numbers using the

range ( ) function

While Loop

Keeps running as long as the condition is true.

Enter While Loop

Condition

T/F

Back to Condition

False

True

Exit Loop

While Loop

  • Used when you don't know beforehand the number of times to iterate
  • While loops starts with the keyword while
  • The condition is checked first and only enters the loop body if the condition evaluates to true
  • Process continues until the condition evaluates to false
  • Infinite loop occurs when the condition never evaluates to false

Break and Continue

  • When you want to terminate the current iteration or the entire loop without checking the test condition

Alternating the flow of a loop

Break Statement

Terminates the loop

Condition

T/F

Break

Y/N

Back to Condition

Enter Loop

False

True

Yes

No

​Exit Loop

Break Statement

Break statement in a for loop

Break statement in a while loop

Continue Statement

Skips the current code block and returns back to the loop

Condition

T/F

Continue

Y/N

Back to Condition

Enter Loop

False

True

Yes

No

​Exit Loop

Continue Statement

Continue statement in a for loop

Continue statement in a while loop

practice!

Made with Slides.com