# Syntax cheat sheet¶

In [ ]:
# Functions: they are only run when called and are used to repeat work

# A function can have 0, 1, or as many arguments as you want.
def FUNCTION_NAME(ARGUMENT1, ARGUMENT2, ...):
FUNCTION_BODY # Optional
return FUNCTION_VALUE # Technically optional, but you should always put a return

In [2]:
# Examples of functions

# The identity function
def identity(x):
return x

# A function that sums 0 to x, inclusive
def sumToXInclusive(x):
s = 0
for i in range(x + 1):
s += i
return

In [3]:
# Example of calling a function

sumToXInclusive(5)

Out[3]:
15
In [ ]:
# Control flow: control flow is used to change the behavior of a program based on a condition

# CONDITION are expressions that result in boolean values

# Exactly 0 or 1 of the bodies will execute
# While elif and else are optional, if you have them, the bodies are not

if CONDITION1:
IF_BODY # NOT optional
# elifs are optional, and you can have as many of them as you want
elif CONDITION2:
ELIF_BODY
# the else is optional and is a catch all. If no other bodies execute, the else body will execute
else:
ELSE_BODY

In [ ]:
# Examples of control flow

if True:
print('This will print')

if False:
print('This will NOT print')
else:
print('This will print')

if True:
print('This will print')
elif True:
print('This will NOT print')

In [ ]:
# For loops: used for repetitive behavior over an array, string, or range

for VARIABLE in {LIST, STRING, range}:
LOOP_BODY

In [ ]:
# Examples of for loops

for i in [4, 6, 1]:
print(i)

for x in 'mango':
print(x)

for x in range(5):
print(x)

In [ ]:
# While loops: used for repetitive behavior

# WARNING: they can run forever, be careful of how you use them

while CONDITION:
WHILE_LOOP_BODY

In [ ]:
# While loop example

i = 0
while i < 10:
print(i)
i += 1