# Functions and Selections

A lecture by Alex

# Functions

Note: Functions always return one thing (we can combine things into one thing)

Functions have 3 parts:

• name
• arguments
• body

## Def

Stands for “define”. It’s what makes a function a function.

## Name

Any valid identifier.
(Starts with a letter, contains only letters, underscores, and numbers)

`def quadratic`

## Arguments

List (can be empty) of inputs.

`def quadratic(a,b,c):`

## Body

Entire body is one indent deeper than the definition.
One expression per line.

``````def quadratic(a,b,c):
print(a, b, c)
d = (b*b-4*a*c)**.5
return (-b+d)/(2*a), (-b-d)/(2*a)
``````

## Comments

If you want a good grade, add them.

``````# the quadratic formula
def quadratic(a,b,c):
print(a, b, c) # display a, b, and c
d = (b*b-4*a*c)**.5 # reuse the part inside the square root
return (-b+d)/(2*a), (-b-d)/(2*a) # return both roots
``````

# Booleans

True and False

## Boolean statements

“selection statements” are just normal operators like +, -, /, * but return booleans instead of numbers.
The standard built-in operators that return booleans are:

• >, <, <=, >=
• ==, !=
• or
• and

With a special mention of `not`, which simply inverts a boolean expression.
`print((not True) == False)` –> True
`print(True == (not False))` –> True

# If statements

``````# return if a is between x and y (exclusive)
def between(a,x,y):
if a > x: # a is greater than x
if a < y: # a is less than y
return True
return False
``````

## Better example: Return the maximum of 3 numbers

``````# return the biggest number
def biggest(a,b,c):
if a > b: # a is bigger than b
if a > c: # a is also greater than c
return a
else: # c is greater than a
return c
elif b > c: # a is NOT greater than b and b is bigger than c
return b
else: # a is NOT greater than b and b is NOT greater than c
return c
``````

(Always choose the highest option on this flowchart, that’s where the “else” is)

# Active learning

## Uno

Consider a simplified game of UNO that has forty different cards.

Each card has a color (“red”, “yellow”, “green” or “blue”) and a value (0, 1, 2, 3, 4, 5, 6, 7, 8 or 9).

Complete the boolean function below so that it returns True if the second card can be played on the first card and False otherwise.

`def legal_play(first_value, first_color, second_value, second_color):`

For example, legal_play(3, “blue”, 3, “green”) and legal_play(5, “yellow”, 7, “yellow”) should both return True, but legal_play(9, “red”, 6, “green”) should return False.

### Uno rules btw

Either the color or number has to match

Hint: (I italicized either and or for a reason)

## Turtle

Take key-events.py and modify it so that the turtle only moves if it will still be visible. Use one boolean function in your solution.