IST256 : Applications Programming for Information Systems Loops: Iterating over Code
Agenda Connection Activity Teaching: Practice Activity While Loops For Loops Practice Activity Guess a Number
Connect Activity Full-Contact Kahoot!: Let’s prepare for the quiz with a game of Kahoot! Top 3 Get a Prize! https://play.kahoot.it/#/?quizId=7a1ac0ce-d02c-45b6-84e7-b4680b5aa1e6
Anatomy of a loop A Loop is a sequence of code that repeats as long as a Boolean expression is True. The sequence of code that repeats is known as the Body. The Boolean expression which is tested is known as the Test Condition or Exit Condition. Variables which are part of the Test condition are called Loop Control Variables. If the Test condition value never changes, the loop will continue forever. This is called an Infinite Loop. This is why loop control variables should change value in the loop body.
Quick: Watch Me Code Let’s Count to 10. Or 50. Or 100.
Check Yourself: 90 Second Challenge X = “Python” Y = [“Programming”, “Is”, “Fun”] What is: X[3] ? Y[1] ? Y[0][1] ? What is the Test Condition? What is/are the loop control variable(s)? Which line numbers are in the loop body? What is the first value to print? How many times does this loop iterate?
Watch Me Code Password Prompt Example Infinite loops The Break Statement
For Loop The For Loop iterates over a python list or range of numbers. The for loop uses an iterator to select each item from the list or range and take action in the loop body.
Watch Me Code For Loop Example Iterate over a Range Iterate over a list
Check Yourself: 90 Second Challenge Match the Definition… To its term. Add one to a variable Subtract one from a variable Test condition is never false Exit the loop Loop a fixed number of times Break Increment Infinite loop Decrement For
Help me Code Password Program: 5 attempts for the password On correct password, print: “Access Granted”, then end the program On incorrect password “Invalid Password Attempt #” and give the user another try After 5 attempts, print “You are locked out”. Then end the program.
Now You Code Guess a number guessing game between 1 and 100: Use random.randint(1,100) to get a number. Allow a user guess the number If correct say so! If guess too high, say “Lower” If guess too low, say “Higher” After they guess correctly, print number of guesses it took to find the correct number.