Programming

with Snakes (part 6)
and Turtles

If


Sometimes you want to make a decision based on the current state of your application.

Usually this is done using a variable.

Decisions are almost always of the form: "if" something is true do something, otherwise skip it.

There are a few other possibilities, but that is the most of it.

If With Example


if <condition>:
  <do something>

if name == 'Mr. Noye':
  print 'Teacher'

if age < 18:
  print 'half price'

Conditional Operators


<   is less than
<=  is less than or equal to
>   is greater than
>=  is greater than or equal to
==  is equal to
!=  is not equal to 

All of these operators can be used between two values (including variables) to produce a "True" or "False" value.

If one thing otherwise the other


A variation of the "if" statement is the "if ... else" statement.

"if" one thing is true then do a block of code "else" do a different block of code.

if age < 18:
  print 'half price'else:
  print 'full price'

More Else


Sometimes there are a number of different else options. You can use the "elif" (short for "else if")

if age < 18:
  print 'half price'elif age >= 65:  print 'half price'else:
  print 'full price'

Combining Conditionals


You can combine conditionals using "or" and "and".

The previous example can be written as:

if age < 18 or age >= 65:
  print 'half price'else:
print 'full price'

More examples



if sex == 'female':
  if age >= 18:
    print 'Ms.'   # female 18 or over
  else:
    print 'Miss.' # female under 18
else:
  if age >= 18:
    print 'Mr.'   # male 18 or over
  else:
    print 'Mstr.' # male under 18

Still More Examples



if sex == 'female' and age >= 18:
  print 'Ms.'
elif sex == 'female' and age < 18:
  print 'Miss.'
elif sex == 'male' and age >= 18:
  print 'Mr.'
else:
  print 'Mstr.'

Challenge


Draw a row of circles centred on the screen

  • The radius of the circles MUST be in a variable
  • The length of the row MUST be in a variable
  • The circles on the right of centre MUST be draw using a red pen and a yellow fill
  • The circles on the left of centre MUST be drawn using a blue pen and a white fill
Made with Slides.com