Skip to content

Instantly share code, notes, and snippets.

@CrazyPython
Last active August 23, 2016 15:48
Show Gist options
  • Save CrazyPython/a4e07d5bc0feeef132d31bd05b21d64d to your computer and use it in GitHub Desktop.
Save CrazyPython/a4e07d5bc0feeef132d31bd05b21d64d to your computer and use it in GitHub Desktop.
valid code, part three
# Today I'll tell you about FUNCTIONS.
# Often, we need to reuse code because we do similar operations and don't wanna repeat the code every single time
# because that means larger code (that's bad) and awkward and hard to understand code (for humans)
# You call (fancy word for execute) a function using function_name(paremeter1, paremeter2, paremeter3, ...).
# Functions can have anywhere from zero to virtually infinite paremeters
def countdown(start_number):
if start_number > 0: # only do a countdown if the start number is greater than zero
print(start_number) # print the starting number
countdown(start_number-1) # what's this? It's a functions that calls itself!
# How does it work, you ask?
# Well think about it!
# Say we start with some code:
countdown(3)
print("BLAST OFF!!")
# Then it checks if 3 > 0
# Since that's true, we print "3".
# Now we call countdown(2)
# The function again checks if 2 > 0
# Since that's true, we print "2"
# Now we call countdown(1)
# The function again checks if 1 > 0
# Since that's true, we print "1"
# Now we call countdown(0)
# The function again checks if 0 > 0
# It isn't. There isn't any code to execute after "if", so we exit into the next level.
# We go up one level to the code that called the function
# There is no code to execute after that function call, so we exit into the next level.
# and so on until the top most level (`countdown(3)`)
# Then we go up one level to the code that called the function. We step onto the next level.
# The next instruction tells us to write "BLAST OFF!!" to the console.
# the output would be:
# 3
# 2
# 1
# BLAST OFF!
# Note that there isn't a one-second pause between each printed number because we didn't tell the computer to do that
# Remember, it ignores names like "countdown"! The computer doesn't know english. (stupid idiot computer... ^jk)
# If we wanted to do that, we'd need to write `import time` at the top of the file and then `time.sleep(1)` between
# the `print()` and the `countdown(n-1)`
# and in this paragraph, we = computer. Sorry if that was confusing.
# we could've done:
print(3)
print(2)
print(1)
print("BLAST OFF!")
# but that's too manual and boring.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment