Selection CIS 40 – Introduction to Programming in Python

Slides:



Advertisements
Similar presentations
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Chapter 4 Making Decisions
Line Continuation, Output Formatting, and Decision Structures CS303E: Elements of Computers and Programming.
Python – Making Decisions Lecture 02. Control Structures A program that only has one flow is useful but limited. We can use if statements to make these.
Chapter 4 Selection Structures: Making Decisions.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
PROBLEM SOLVING WITH LOOPS Chapter 7. Concept of Repetition Structure Logic It is a computer task, that is used for Repeating a series of instructions.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Decision Making CMSC 201. Overview Today we will learn about: Boolean expressions Decision making.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Chapter Making Decisions 4. Relational Operators 4.1.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Boolean Expressions and Logical Operators CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington Credits:
Chapter 7 Problem Solving with Loops
8. DECISION STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Decision Making CMSC 201 Chang (rev ).
Controlling Program Flow with Decision Structures.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
CompSci 230 S Programming Techniques
Introduction to Decision Structures and Boolean Variables
Control Structures I Chapter 3
Development Environment
REPETITION CONTROL STRUCTURE
Introduction to Python
Line Continuation, Output Formatting, and Decision Structures
Making Choices with if Statements
Chapter 4: Making Decisions.
Lesson 04: Conditionals Topic: Introduction to Programming, Zybook Ch 3, P4E Ch 3. Slides on website.
Upsorn Praphamontripong CS 1110 Introduction to Programming Fall 2016
Topics Introduction to Repetition Structures
Chapter 4: Making Decisions.
EGR 2261 Unit 4 Control Structures I: Selection
The Selection Structure
Variables, Expressions, and IO
Functions CIS 40 – Introduction to Programming in Python
Topics The if Statement The if-else Statement Comparing Strings
Chapter 4: Making Decisions.
Conditionals & Boolean Expressions
Topics The if Statement The if-else Statement Comparing Strings
Conditionals & Boolean Expressions
Line Continuation, Output Formatting, and Decision Structures
Python - Conditional Execution
And now for something completely different . . .
Lesson 04: Conditionals Class Chat: Attendance: Participation
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
File IO and Strings CIS 40 – Introduction to Programming in Python
Scratch: selection / branching/ if / If…else / compound conditionals / error trapping by Mr. Clausen.
Loops CIS 40 – Introduction to Programming in Python
Coding Concepts (Basics)
Introduction to Programming Using Python PART 2
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
CISC101 Reminders All assignments are now posted.
Winter 2019 CISC101 4/16/2019 CISC101 Reminders
Chapter 3: Selection Structures: Making Decisions
Using C++ Arithmetic Operators and Control Structures
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Control Structures.
Presentation transcript:

Selection CIS 40 – Introduction to Programming in Python De Anza College Clare Nguyen

Intro So far our code has run from beginning to end by following one path of execution. Now we learn to write code that presents the computer with several execution paths, and the computer will select one path based on a condition that it evaluates. The condition can come from a user input or a calculation result, or it can come from data in a file, from a device, or from an error that’s been detected. We will start with boolean logic, which is how computers make decisions, then we cover the instructions that tell the computer to make selections.

Boolean Logic When making a selection or a choice, the CPU first evaluates a an expression to True or False. Boolean expressions are expressions that result in True or False. An example of a common Boolean expression: 5 > 3 which is evaluated to True. In Python there are 2 Boolean data values: True and False and they have the bool data type. Example: Any non-zero number is considered True. For example, the Boolean expression 42 is evaluated to True. evaluation of Boolean expressions True and False are data values that have bool data a type

Relational Operators A Boolean expression uses relational operators to compare 2 values, or to see how 2 values are “related” to each other. Here are the list of relational operators and how they work: Note that: = means assign or store data == means equal to greater than or equal to less than or equal to equal to (note that it’s 2 equal signs) not equal to

Logical Operators Logical operators are applied to Boolean expressions. There are 3 logical operators: and, or, not and is used to combine 2 Boolean expressions: num1 > num2 and num2 != 0 The entire expression is True only if both expressions (on the right and left of and) are True. or is used to combine 2 Boolean expressions: num1 > num2 or num2 != 0 The entire expression is False only if both expressions (on the right and left of or) are False. not is used to reverse the logic of a Boolean expression: not (5 > 8) is True not (10 == 10) is False

Order of Operation Adding to our existing table of order of operations: Operators with higher precedence are evaluated first. Operators with the same precedence are evaluated left to right, except for assignments ( = ) which are evaluated right to left. Highest ( ) parentheses ** exponentiation * / % multiply, divide, modulus + – add, subtract < > <= >= inequality compare == != equality compare not logical not and logical and or logical or Lowest = assign (store data)

if Statement The if statement is a conditional instruction, how it runs depends on a condition. In the if statement is a “contract” between us and the CPU: We give the CPU: - a condition (or a Boolean expression) - 2 paths of execution The CPU: - evaluates the Boolean expression - takes only 1 of the paths of execution Example: If the condition (num2 > 0) is True, then the CPU takes Path 1 If the condition (num2 > 0) is False, then the CPU takes Path 2. Path 1 condition Path 2

Flow Chart A flow chart is a diagram that shows the flow of execution. Example code Flow chart: From the flow chart we can see that (num2 > 0) is a decision point. From there, 2 execution paths are possible, and the CPU will choose one path. read num2 print num2 num2 > 0? print positive print negative print conclusion True False

Click for a video demo of how the if statement works

Format of the if Statement (1 of 3) The if statement has the format: if Boolean_expression : True block with 1 or more statements else: False block with 1 or more statements Both True and False blocks must be indented. Both the keywords if and else must line up. Example: The True block’s statements will run if the expression is True. The False block’s statements will run if the expression is False. Only one of the blocks will run.

Format of the if Statement (2 of 3) When the program requirement dictates that the False block is not needed, we can have an if statement with just a True block. if Boolean_expression : True block with 1 or more statements Example requirement: only print to screen if num2 is positive. In this case we don’t want to print if the condition is False, so we remove both the else and the False block. The flow chart for this if statement: If (num2 > 0) is False, then the CPU will go straight to the next statement. False num2 > 0? print positive True

Click for a video demo of an if statement that only has a True block

Format of the if Statement (3 of 3) Be very careful with indentations. Python relies on proper indentation to interpret or translate our code correctly. Given these 2 blocks of code that have the same statements but different indentation, their output are different. Can you see why?

The if … elif Statement When the decision is for one choice out of many choices, we use the if … elif statement: if Boolean_expression_1: True block 1 elif Boolean_expression_2: True block 2 … elif Boolean_expression_N: True block N else: False block In the example, the user has a choice to draw one of the shapes. The last False block is for all user choices that are not one of the valid letters. Example:

The if … elif Statement When the decision is for one choice out of many choices, we use the if … elif statement: if Boolean_expression_1: True block 1 elif Boolean_expression_2: True block 2 … elif Boolean_expression_N: True block N else: False block In the example, the user has a choice to draw one of the shapes. The last False block is for all user choices that are not one of the valid letters. Example:

Click for a video demo of the if … elif statement

The Nested if Statement A True and/or False block can contain another if statement. This is called a nested if. The inner if statement is nested inside the outer if statement. if Boolean_expression1: if Boolean_expression2: Do task A else: Do task B else: Do task C Task A runs when Boolean_expression1 and Boolean_expression2 are both True. Task B runs when Boolean_expression1 is True but Boolean_expression2 is False. Task C runs when Boolean_expression1 is False. outer if inner if

Click for a video demo of the nested if statement

Exception Handling (1 of 3) When the CPU is running our code and suddenly it encounters an error such that it cannot successfully complete the current instruction, it will stop running the code. This is known as an exception. Example of an exception that we’ve seen earlier in the quarter: In this example, the CPU cannot successfully divide by num2, so it stops and sends out an error message. Ideally we want to catch this exception so that we can tell the computer to do something about the error, instead of print the unfriendly message above and quit on us.

Exception Handling (2 of 3) When we write code that can cause an exception: 1) we ask Python to try running the code, and 2) we write an except block of code that will be run if the exception happens. Going back to our example code: The try except construct causes 2 paths to exist in the execution flow. If there is no exception, then the division is successful and execution skips the except block and continues. If there is exception, then the except block runs and our error message is printed. Then execution continues. except block runs if an exception occurs code that can cause an exception is put in a try block

Exception Handling (3 of 3) Looking at a more complete example and the flow chart Script output when num2 is 2: Script output when num2 is 0: store data print status try divide? print error Exception OK print result Exception is handled: friendly error message and execution continues.

What’s Next In this module we learned to write code that can make choices based on conditions that occur during run time. This makes the code more adaptable and more user friendly. In the next module we learn the last construct in programming, loops, so that we can make the code even “smarter.”