1 of 17

Explore Python 1

Conditionals

Compared with Scratch

2 of 17

Understanding conditionals correctly is very important...

A programmer's wife tells him: "Run to the store and pick up a loaf of bread. And if they have eggs, get a dozen".

The programmer comes home with 12 loaves of bread.

What does the programmer get from the store?

3 of 17

Conditionals 1

  1. In an if statement
    1. The line ends with :
    2. And there is an indent on the condition line(s)
  2. comparing for equality is == (and >=, <=, != )
  3. if you compare strings you have to use " " (or ' ')

Scratch

Python

Defensive programming:

  1. Spell out expected input options

4 of 17

Conditionals 2

If condition1 :

do things

elif condition2 :

do others

else:

do this

Zoom Poll: Which one is better? Why?

Program 1 Program 2

Python

If condition1 :

do things

elif condition2 :

do others

elif condition3 :

do this

What’s the difference?

Defensive programming:

2. Do something with unexpected input

If condition1:

do things

else:

do other things

5 of 17

Nested Conditionals 2.1

The elif Clause (fun fact :)

You may have noticed that the keyword is spelled ‘elif’, without ‘se’. If you write it as “elseif”, with ‘se’, Python will tell you that it is not the correct spelling.

Why not? Because Guido van Rossum (the inventor of Python) said so.

In fact, Guido resisted any suggestion that it even be permitted as a valid alternative spelling. He said:

“If you want to spell it with ‘se’, you may do it very simply:

Step 1—Make up your own language.

Step 2—Make it popular.”

Case AB:

Case CDE:

Case FGH:

6 of 17

Nested Conditionals 2.5

Exercise 1 ---->>>

What will be printed if you

un/comment the various values of

a_variable and b_variable?

Predict what

will be printed, and write your predictions as comments in the Trinket (under the heading “Exercise 1”).

You may want to run the code to verify your predictions.

Case AB:

Case CDE:

Case FGH:

Zoom Poll

New Trinket:

Explore Python 1

7 of 17

Exercise: Conditionals 3

Remember:

  • Don’t forget type conversions!
  • In an if statement
    • The line ends with :
    • And there is an indent on the condition line(s)
  • comparing for equality is ==
  • if you compare strings you have to use “ ” (or ‘ ‘)
  • round() the result to 1 digit after the decimal point

The common temperature scales are Celsius (C), Fahrenheit (F), Kelvin (K).

(Did you hear about the man who was cooled to absolute zero? He's 0K now :)

Python

Exercise 2:

Temperature Conversion

Do defensive programming:

  • Spell out input options
  • Do something with unexpected input

8 of 17

Conditionals 4

  1. Make sure to check that the number of diners is an integer (and not a float)

Hint: use mod (the % operator). Run the following and figure out how to use mod based on the result of the code below (try different numbers of diners, like 3, 3.7, 5, 5.1, to see what the results are):

diners = float(input("how many diners?"))

print diners % 1

  • Make sure you print the amount in dollars and cents.

Hint: use the round() built-in Python function, to print just 2 decimal places, e.g., 23.45

Scratch

Python

else:

you do the hard math … :)

Exercise 3 - fix & enhance with defensive programming

9 of 17

Conditionals 5

  1. What’s wrong with the following program?
  2. Fix it
  3. Make it more “robust” to user errors (use “defensive programming”)
  4. Add support for “multiply” and “divide”
  5. Make sure to check for division by 0 (and obviously, don’t do it, if it’s zero!)

Exercise 4:

Extra Experience: add “raising to the power” (exponentiation) operation:

look up the math operation for that

10 of 17

Conditionals with Logic

You can use more sophisticated conditions with the ‘if’ statements.

E.g. (on an assembly line or a factory):

weight = float(input(“what’s the part weight?”) # lbs.

height = int(input(“what’s the part height?”) # inches

color = input(“what’s the part color?”) # color name

if weight > 15 and height < 50 and color == ‘purple’:

print ‘This part does not fit the bill’

else:

print ‘This is the correct part!’

You can use logic operations like: and or not

You can use math comparisons like: == != <= >=

Exercise 5

You are driving a little too fast, and a police officer stops you. Write code to compute the result (getting a ticket :(, by printing “no ticket”, “small ticket”, or “big ticket”, depending on the speed (see below):

If speed is 65 or less, the result is “no ticket”. If speed is between 66 and 80 inclusive, the result is “small ticket”. If speed is 81 or more, the result is “big ticket”. Unless it is your birthday, in which case, the policeman will be stricter and your speed needs to be 5 lower in all cases (e.g., you need to drive between 61 and 75 to get “small ticket”, and so on).

11 of 17

Extra Fun (and Experience) with conditionals

Do all the sections in Ex. Ex. 3 - More conditionals in the doc

Explore Python 2 (Trinket) - Ex. Ex. 3

When done with conditionals, create a new Trinket, and try to figure out how to draw shapes by starting to explore

Python Turtle Graphics. (or on GD)

12 of 17

Extra Fun (and Exploring) with Turtles

When done with conditionals, create a new Trinket, and try to figure out how to draw shapes by starting to explore

Python Turtle Graphics. (or on GD)

13 of 17

Backup slides

This is the end of the presentations.

Proceed at your own risk :)

14 of 17

This is (almost) a blank slide :)

15 of 17

Partial Solution: Conditionals 2

Remember:

  • Don’t forget type conversions!
  • In an if statement
    • The line ends with :
    • And there is an indent on the condition line(s)
  • comparing for equality is ==
  • if you compare strings you have to use “ ” (or ‘ ‘)

Scratch

Python

Question: Explore Python 2

Example of “nagging the user” for a correct input - see notes

Do defensive programming:

  • Spell out input options
  • Do something with unexpected input

16 of 17

Scratch

17 of 17

FunFact: Algorithm for supporting equality-check ==

http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

11.9.3 The pseudocode for the Equality Comparison Algorithm in JavaScript

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

  1. If type(x) is the same as type(y), then
    • If type(x) is Undefined, return true.
    • If type(x) is Null, return true.
    • If type(x) is Number, then
      1. If x is NaN, return false.
      2. If y is NaN, return false.
      3. If x is the same Number value as y, return true.
      4. If x is +0 and y is −0, return true.
      5. If x is −0 and y is +0, return true.
      6. Return false.

(continued on the right …)

    • If type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions). Otherwise, return false.
    • If type(x) is Boolean, return true if x and y are both true or both false. Otherwise, return false.
    • Return true if x and y refer to the same object. Otherwise, return false.
  • If x is null and y is undefined, return true.
  • If x is undefined and y is null, return true.
  • If type(x) is Number and type(y) is String,�return the result of the comparison x == ToNumber(y).
  • If type(x) is String and type(y) is Number,�return the result of the comparison ToNumber(x) == y.
  • If type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
  • If type(y) is Boolean, return the result of the comparison x == ToNumber(y).