Flow Control I Branching and Looping
Flow Control Programs normally execute from beginning to end Flow control statements allow branching and looping Today: For Loops If Statements
For Loop Use a for loop to repeat a group of statements a desired number of times Here's an example: import turtle for i in [1, 2, 3, 4]: turtle.forward(50) turtle.right(90) This loop repeats 4 times (once for each value in the list). What does the turtle draw? List of values
For Loop Variable Use the loop variable if you want to know which value in the list the loop is processing: import turtle for i in [1, 2, 3, 4]: print("Now drawing side #", i) turtle.forward(50) turtle.right(90) Each time the loop body executes, the loop variable (i) takes on the next value in the list The loop variable does not have to be created separately before the loop begins Loop variable Loop body
Sum a List of Numbers Notes: sum = 0 for num in [5, 10, 15, 20]: print('Processing number:', num) sum = sum + num print("The sum of the numbers is: ", sum) Notes: Indentation determines which lines are included in the loop All lines inside the loop must be indented the same number of spaces Lines before and after the loop must be left-aligned Alignment is important!
The range() Function We want the turtle to draw a circle. How? import turtle for i in range(72): turtle.forward(10) turtle.right(5) range(72) generates a list of 72 values numbered [0, 1, 2, ..., 71]
range() options Range can: Remember: Count from a number other than 0 for i in range(-3, 3): # [-3, -2, -1, 0, 1, 2] Count by intervals for i in range(1, 10, 2): # [1, 3, 5, 7, 9] Count down for i in in range(5, 0, -1): # [5, 4, 3, 2, 1] Remember: range() always omits the final value interval
Branching
Making Decisions Remember our simple actuarial calculator? ageStr = input("How old are you?") age = int(ageStr) yearsLeft = 80 - age print("You may have about", yearsLeft, "years of life left.") Let's enhance this so it handles negative input appropriately.
if Statement The if statement is used to make a decision based on a comparison age = int(input("How old are you?")) if age > 0: yearsLeft = 80 - age print("You may have about", yearsLeft, "years of life left.") else: print("I need a positive age.") If the comparison age > 0 is true, the "true statements" are executed. Otherwise, the "false statements" are executed True Statements False Statements
Anatomy of if statement if comparison : true statements else: false statements Note: else section is optional colons are required comparison consists of two expressions comparison operator Don't forget the colons! Operator Meaning == Equal to != Not equal to < Less than <= Less or equal > Greater than >= Greater or equal
Comparing Strings Remember to use quotes when comparing a variable to a string name = input("What's your name?") if name != "": print('Hello,', name, '!') else: print("You didn't enter a name!")
Let's write a Grading Assistant The instructor needs help converting letter grades to a numeric score Write a program that Prompts user to enter letter grade (A, B, or C) Chooses appropriate numeric score Displays result
Grading Assistant # Grading assistant letterGrade = input("Enter letter grade (A, B, or C):") score = 0 if letterGrade == 'A': score = 100 if letterGrade == 'B': score = 85 if letterGrade == 'C': score = 70 if score > 0: print("Give 'em a", score) else: print('Invalid letter grade entered.')
A Revised Grading Assistant The instructor needs help converting a numeric score to a letter grade Write a program that Prompts user to enter numeric score Chooses appropriate letter grade (A, B, C, or F) Displays result
Revised Grading Assistant (First Attempt) # Revised Grading Assistant score = int(input("Enter score (0 - 100):")) grade = 'F' if score >= 90: grade = 'A' if score >= 80: grade = 'B' if score >= 70: grade = 'C' print("Give 'em a(n)", grade) What's the output for: score = 75? score = 50? score = 100? "Houston, we have a problem..." We need a way to choose exactly one of four alternatives
If Statements With Multiple Alternatives An if statement can choose exactly one of several alternatives Use elif ("else if") for each alternative Use a final (optional) else to handle cases that didn't match any of the conditions The first case that matches is executed; the rest are skipped # Revised Grading Assistant (Correct) score = int(input("Enter score (0 - 100):")) if score >= 90: grade = 'A' elif score >= 80: grade = 'B' elif score >= 70: grade = 'C' else: grade = 'F' print("Give 'em a(n)", grade)