Making decisions with code

Slides:



Advertisements
Similar presentations
Computer Science 1620 Programming & Problem Solving.
Advertisements

Administrative MUST GO TO CORRECT LAB SECTION! Homework due 11:59pm on Tuesday. 25 points off if late (up to 24 hours) Cannot submit after 11:59pm on Wednesday.
Chapter 4 Selection Structures: Making Decisions.
22/11/ Selection If selection construct.
Chapter 3: Branching and Program Flow CSCI-UA 0002 – Introduction to Computer Programming Mr. Joel Kemp.
Conditional Statements.  Quiz  Hand in your jQuery exercises from last lecture  They don't have to be 100% perfect to get full credit  They do have.
Decision Structures, String Comparison, Nested Structures
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 11 So Many Paths … So Little Time.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
Design A software design specifies how a program will accomplish its requirements A design includes one or more algorithms to accomplish its goal.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
JavaScript: Conditionals contd.
BIT116: Scripting Lecture 05
Introduction to Decision Structures and Boolean Variables
Basic concepts of C++ Presented by Prof. Satyajit De
Whatcha doin'? Aims: To start using Python. To understand loops.
CS0007: Introduction to Computer Programming
Data Types Variables are used in programs to store items of data e.g a name, a high score, an exam mark. The data stored in a variable is entered from.
Chapter 4: Making Decisions.
Chapter 4 (Conditional Statements)
Programming Mehdi Bukhari.
Debugging and Random Numbers
IF statements.
CS1371 Introduction to Computing for Engineers
The Selection Structure
Programming 101 Programming for non-programmers.
Unit 1 Day 1: Solving One- and Two-Step Equations
If, else, elif.
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
Handling errors try except
Javascript Conditionals.
An Introduction to Programming with C++ Fifth Edition
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Conditional Execution
Conditional Statements
Decision Structures, String Comparison, Nested Structures
Selection CIS 40 – Introduction to Programming in Python
Python - Conditional Execution
File Handling Programming Guides.
Conditions and Ifs BIS1523 – Lecture 8.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Decision Structures, String Comparison, Nested Structures
Writing Methods AP Computer Science A.
Conditional Execution
Introduction to Programming using Python
If selection construct
Introduction to TouchDevelop
Conditional Execution
Remembering lists of values lists
If selection construct
Logical Operations In Matlab.
Algorithm and Ambiguity
Conditional Logic Presentation Name Course Name
The if Statement Control structure: logical design that controls order in which set of statements execute Sequence structure: set of statements that execute.
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Flowcharts and Pseudo Code
Chapter 3: Selection Structures: Making Decisions
Simple Branches and Loops
The Selection Structure
Data Types and Maths Programming Guides.
Python Selection.
Starter Activities GCSE Python.
The while Looping Structure
Lecture 5 – Unit 1 – Chatbots Python – More on Conditional statements
How to read from a file read, readline, reader
3.0 - Design A software design specifies how a program will accomplish its requirements A design includes one or more algorithms to accomplish its goal.
Flow Control I Branching and Looping.
Working with dates and times
Presentation transcript:

Making decisions with code if statements Susan Ibach | Technical Evangelist Christopher Harrison | Content Developer

Every day we are faced with decisions Should I drive or take the bus? Should I cook at home or go out for dinner? Which laptop should I buy?

The choice we make depends on different conditions Should I drive or take the bus? Am I late? What’s the price of gas? Should I cook at home or go out for dinner? Do I have any food at home? Do I have enough money to go out? Which laptop should I buy? How much RAM do I need? How much money do I have?

If your code is going to solve problems, it has to make decisions as well If the user maintained a bank account balance over $1000 waive the transaction fees If a user cancels their appointment less than 24 hours before the appointment time, charge a cancellation fee If the hockey player gets the puck in the net, add one to the score

If statements allow you to specify code that only executes if a specific condition is true answer=input("Would you like express shipping?") if answer == "yes" :     print("That will be an extra $10") What do you think the == symbol means?

You can use different symbols to check for different conditions == is equal to != is not equal to < is less than > is greater than <= is less than or equal to >= is greater than or equal to if answer == "yes" : if answer !=  "no" : if total < 100 :  if total > 100 : if total <= 100 : if total >= 100 :

If statements allow you to specify code that only executes if a specific condition is true answer=input("Would you like express shipping? ") if answer == "yes" :     print("That will be an extra $10") print("Have a nice day") Does it matter if that print statement is indented? YES – the indented code is only executed if the condition is true

if statements

Real world if statements

Almost every if statement can be written two ways if answer == "yes" : if not answer == "no" : if total < 100 : if not total >= 100 : Which do you prefer?

Write it the way you would say it If course is completed – send certificate to student if courseCompleted == "yes" : If order total under $50 – add shipping if total < 50 : If cat has not been vaccinated – call owner to set appointment if not vaccinated ==  "yes" :

What do you think will happen if we type “YES” instead of “yes” answer=input("Would you like express shipping? ") if answer == "yes" :     print("That will be an extra $10") print("Have a nice day") One of the challenges of working with strings of characters, is that the computer considers “y” and “Y” to be two different letters.

Is there a way we could change a string from uppercase to lowercase? answer=input("Would you like express shipping?") if answer.lower() == "yes" :     print("That will be an extra $10") print("Have a nice day") Hint: There were functions we could call for string variables Hint: lower()

What if we try an if statement with numbers instead of strings deposit = 150 if deposit > 100 :     print("You get a free toaster!") print("Have a nice day") What will appear on the screen if deposit is 150? What will appear on the screen if deposit is 50? What will appear on the screen if deposit is exactly 100?

Working with numeric values and if statements

Always test >,< and boundary conditions deposit = 150 if deposit > 100 :     print("You get a free toaster!") print("Have a nice day") So when you test this code, try: a value less than 100 a value greater than 100 exactly 100

Handling user input

Asking the user for a numeric value to use in an if statement

How could we let the user enter the amount to deposit? deposit=input("How much would you like to deposit? ") if deposit > 100 :     print("You get a free toaster!") print("Have a nice day") Why did our code crash? How can we fix it?

We have to convert the string value returned by the input function to a number deposit=input("How much would you like to deposit? ") if int(deposit) > 100 :     print("You get a free toaster!") print("Have a nice day") Here is another way to do the same thing deposit=int(input("How much would you like to deposit? ")) if deposit > 100 :

Branching

What if you get a free toaster for over $100 and a free mug for under $100 deposit=input("How much would you like to deposit? ") if float(deposit) > 100 :     print("You get a free toaster!") else: print("Enjoy your mug!") print("Have a nice day") The code in the else statement is only executed if the condition is NOT true What will appear on the screen if we enter 50? 150? 100?

Adding an else clause

You can use boolean variables to remember if a condition is true or false deposit= input("how much would you like to deposit? ") if float(deposit) > 100 :     #Set the boolean variable freeToaster to True     freeToaster=True #if the variable freeToaster is True  #the print statement will execute if freeToaster :     print("enjoy your toaster") Make sure you test what happens when your if statement is true and what happens when your if statement is false.

Using a Boolean variable and testing all paths

Why does our code crash when we enter a value of 50 for a deposit? deposit= input("how much would you like to deposit? ") if float(deposit) > 100 :     #Set the boolean variable freeToaster to True     freeToaster=True #if the variable freeToaster is True  #the print statement will execute if freeToaster :     print("enjoy your toaster") Look at the error message: Name ‘freeToaster’ is not defined.

It’s always a good idea to initialize your variables! #Initialize the variable to fix the error freeToaster=False deposit= input("how much would you like to deposit? ") if float(deposit) > 100 :     #Set the boolean variable freeToaster to True     freeToaster=True #if the variable freeToaster is True  #the print statement will execute if freeToaster :     print("enjoy your toaster")

Aren’t you just making the code more complicated by using the Boolean variable? That depends… What if you are writing a program, and there is more than one place you have to check that condition? You could check the condition once and remember the result in the Boolean variable What if the condition is very complicated to figure out? It might be easier to read your code if you just use a Boolean variable (often called a flag) in your if statement

And now we have more ways to make typing mistakes! Can you find three? deposit=input("How much would you like to deposit? ") if float(deposit) > 100      print("You get a free toaster!") freeToaster=true else: print("Enjoy your mug!") print("Have a nice day") deposit=input("How much would you like to deposit? ") if float(deposit) > 100 :     print("You get a free toaster!") freeToaster=True else: print("Enjoy your mug!") print("Have a nice day")

Your challenge Calculate shipping charges for a shopper Ask the user to enter the amount for their total purchase If their total is under $50 add $10, otherwise shipping is free Tell the user their final total including shipping costs and format the number so it looks like a monetary value Don’t forget to test your solution with a value > 50 a value < 50 a value of exactly 50

Congratulations! Your code can now react to different conditions! You can now solve problems that require decision making