Flow Control I Branching and Looping.

Slides:



Advertisements
Similar presentations
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Advertisements

Geography 465 Assignments, Conditionals, and Loops.
Chapter 2 - Algorithms and Design
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
Chapter 2 - Algorithms and Design print Statement input Statement and Variables Assignment Statement if Statement Flowcharts Flow of Control Looping with.
1 Chapter 2 - Algorithms and Design print Statement input Statement and Variables Assignment Statement if Statement Flowcharts Flow of Control Looping.
COMP Loop Statements Yi Hong May 21, 2015.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1.
CMSC201 Computer Science I for Majors Lecture 07 – While Loops
Control Structures I Chapter 3
Chapter 4 Selections © Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
CNG 140 C Programming (Lecture set 3)
Line Continuation, Output Formatting, and Decision Structures
Lesson 4 - Challenges.
Chapter 4: Making Decisions.
Python: Control Structures
IF statements.
Summary Conditional: if .. else New Nested conditional elif
ITM 352 Flow-Control: if and switch
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Chapter 4: Making Decisions.
Chapter 6: Conditional Statements and Loops
Logical Operators and While Loops
Control Statement Examples
Control Structure Senior Lecturer
Line Continuation, Output Formatting, and Decision Structures
Introduction to Programming
And now for something completely different . . .
Decision Structures, String Comparison, Nested Structures
Additional Control Structures
Chapter 7 Additional Control Structures
Michael Ernst UW CSE 140 Winter 2013
3 Control Statements:.
Introduction to Programming
More Looping Structures
Topics Introduction to Repetition Structures
CMSC201 Computer Science I for Majors Lecture 09 – While Loops
Comparing Strings Strings can be compared using the == and != operators String comparisons are case sensitive Strings can be compared using >, =, and.
Conditional and iterative statements
Computing Fundamentals
Relational & Logical Operators, if and switch Statements
Topics The if Statement The if-else Statement Comparing Strings
M150: Data, Computing and Information
Introduction to Repetition Structures
SELECTIONS STATEMENTS
CprE 185: Intro to Problem Solving (using C)
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Logical Operators and While Loops
CS2011 Introduction to Programming I Selections (I)
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
CHAPTER 5: Control Flow Tools (if statement)
Chapter 3: Selection Structures: Making Decisions
Making decisions with code
Loops.
Chapter 2 - Algorithms and Design
Relational and Logical Operators
Introduction to Programming
More Looping Structures
Relational and Logical Operators
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
CprE 185: Intro to Problem Solving (using C)
Control Structures.
Data Types and Expressions
Flow Control II While Loops.
Dealing with Runtime Errors
Presentation transcript:

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)