Skip to content

Instantly share code, notes, and snippets.

@beshad
Last active February 20, 2021 13:55
Show Gist options
  • Select an option

  • Save beshad/a95b84237ec262eed9bfd0827bec6282 to your computer and use it in GitHub Desktop.

Select an option

Save beshad/a95b84237ec262eed9bfd0827bec6282 to your computer and use it in GitHub Desktop.
Coding for kids Python - Lesson 5
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "Coding for kids Python - Lesson 5",
"provenance": [],
"collapsed_sections": [],
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/beshad/a95b84237ec262eed9bfd0827bec6282/coding-for-kids-python-lesson-5.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1Mydl5AICWf3",
"colab_type": "text"
},
"source": [
"# Reusable code\n",
"\n",
"At the core of coding is the concept of ***reusability***, or how easy it is to use something again and again. We write code that can do repetitive, complex, or time-consuming things for us, but if we had to write it every single time we needed to use it, coding wouldn't be very useful. \n",
"\n",
"Functions and modules provide a way for us to write code that's reusable. Most programs are made up of one or many modules, and each of those modules is usually made up of several functions. Let's see how writing code in this way helps us have smarter programs.\n",
"\n",
"**Functions**\n",
"\n",
"As we've learned, functions are reusable blocks of code that can do something specific or return a value. Usually, we write functions for things that we often repeat. Let's say we needed to greet a person every time they used our program. We could write a **print( )** function every single time we needed to greet them:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "W7bpNdOvFXQD",
"colab_type": "code",
"colab": {}
},
"source": [
"print(\"Hello, person!\")\n",
"print(\"Hello, person!\")\n",
"print(\"Hello, person!\")"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "__U6jlxwFdcU",
"colab_type": "text"
},
"source": [
"Or we could move this action of greeting a person into a function:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "O93_xKVgFkEA",
"colab_type": "code",
"colab": {}
},
"source": [
"def greet():\n",
" print(\"Hello, person!\")"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "zDAC8FJFFrqv",
"colab_type": "text"
},
"source": [
"Which we can now use any time by writing code like this:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "WEH_DvZNFwsH",
"colab_type": "code",
"outputId": "f97fcf48-d376-4f24-cda0-c5bd1ed304c4",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"source": [
"greet()"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"Hello, person!\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "UyDpvKzzF7eX",
"colab_type": "text"
},
"source": [
"Here's what's happening: To create a function, we first need to describe what will be called and what it will do. We start by using the **def** keyword, which signals to the computer that we are writing a function, it's short for define. Just like a dictionary defines what a word means, we define what our function will do when we use the **def** keyword.\n",
"\n",
"Next, we name our function. Because we will be greeting people when we use this function, the name \"greet\" is a good choice, as it clearly describes what our function is doing. We then add some parentheses () to our function name. We may add parameters in the parentheses later, but for now, we don't have any. Lastly, a colon (:) shows that the following indented lines of code will be part of our function. That's it!\n",
"\n",
"An important thing to know about functions is that they don't run on their own. This means that whenever a computer comes across one, it automatically skips the code whinin it. In order to actually use a function, it needs to be ***called***, meaning we must clearly tell the computer to start executing the called function's code. If we don't call functions, the code within them will never be run!"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ujS1mavKIvxZ",
"colab_type": "text"
},
"source": [
"**Parameters**\n",
"\n",
"Our **greet( )** function is pretty normal. We say \"Hello, person!\" whenever we call it. But what if we wanted to greet the person by their name, instead of the word \"person\"? That would be a much nicer greeting, wouldn't it? Parameters are just the thing we need to add our function in order to do this! A ***parameter*** is a piece of input data we give to a function to do something with. A function can have no parameters, just like our origonal **greet( )** function, or it can have one or more parameters. When we create functions that use parameters, we say that these functions accept parameters, which lets us know that the function can take pieces of input data. \n",
"\n",
"To make our **greet( )** function a little nicer, let's have it accept one parameter called **name** and then use it in our greeting! We add a parameter to a function by placing it in between the parentheses that come after the function name, like this:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "L-zOF6_lYEUn",
"colab_type": "code",
"colab": {}
},
"source": [
"def greet(name):\n",
" print(\"Hello, person!\")"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "dsVjoHmuYLNp",
"colab_type": "text"
},
"source": [
"By adding this parameters to the function, we are now able to use it within our function. This means we can do something like this:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "bcCKoCKJYYZR",
"colab_type": "code",
"colab": {}
},
"source": [
"def greet(name):\n",
" print(f\"Hello, {name}!\")"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "oUqu1uyNYf6N",
"colab_type": "text"
},
"source": [
"Now, when we call our **greet( )** function, it will use the parameter you pass into it, meaning this code:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "Wo0a3dntYuJK",
"colab_type": "code",
"outputId": "87d2a95e-6875-4063-9098-afc1e9aabf7a",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"source": [
"greet(\"Adrienne\")"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"Hello, Adrienne!\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Y0QDO2CP-RhT",
"colab_type": "text"
},
"source": [
"Pretty cool! You know what, though? We can make our **greet( )** function even cooler. Let's decide that we not only want to greet someone by their name, but that we also want to change our greeting deponding on the person. We might say, \"What's up, Adrienne? Nice to see you again!\" if we're greeting someone we know very well, or \"Hello, Duke! Nice to meet you!\" if it's someone new.\n",
"\n",
"Remember, code is all about reusability, so we're already ahead of the game by putting our greeting into a function. We just have to change it a little bit to do these other things we mentioned! To start, let's add another parameter to our **greet( )** function. We'll add a parameter called **is_new**, which can tell the function whether the person we are greeting is someone we know:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "n8r9DY9aAl41",
"colab_type": "code",
"colab": {}
},
"source": [
"def greet(name, is_new):\n",
" print(f\"Hello, {name}!\")"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "bafCg7c-A4HM",
"colab_type": "text"
},
"source": [
"Great! Now, we just need to add some logic to our function. Remember, we want to print a different greeting for the people we know than the one we print for the people we don't know. In this case, we can use our newly added **is_new** parameter to help us make this decision! So, if we don't know the person, we can use a specific greeting.\n"
]
},
{
"cell_type": "code",
"metadata": {
"id": "u0qZNuGJBeXf",
"colab_type": "code",
"colab": {}
},
"source": [
"def greet(name, is_new):\n",
" if(is_new):\n",
" print(f\"Hello, {name}! Nice to meet you!\")"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "AyS08WBBBq3g",
"colab_type": "text"
},
"source": [
"Otherwise, we'll use the friendlier greeting:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "08vt5Q25B2Gq",
"colab_type": "code",
"colab": {}
},
"source": [
"def greet(name, is_new):\n",
" if(is_new):\n",
" print(f\"Hello, {name}! Nice to meet you!\")\n",
" else:\n",
" print(f\"What's up, {name}? Nice to see you again!\")"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "-7Vas2jECK5p",
"colab_type": "text"
},
"source": [
"That's it! Now, when we use our **greet( )** function, we just need to pass in a few inputs for the parameters, and it can do the rest of the work for us! Using the parameters we pass in, the computer can decide which greeting to use. We can also call our **greet( )** function as many times as we want, and it will print out a greeting every time."
]
},
{
"cell_type": "code",
"metadata": {
"id": "ZPN7BoaKC9S3",
"colab_type": "code",
"outputId": "2bddf4c8-d9eb-42a8-d671-6d58b8884d3b",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"source": [
"greet(\"Adrienne\", False)"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"What's up, Adrienne? Nice to see you again!\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "aEY6MCLWDHNz",
"colab_type": "code",
"outputId": "6159398c-360d-46bd-e1a6-076360eeeae4",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"source": [
"greet(\"Duke\", True)"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"Hello, Duke! Nice to meet you!\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "PLfVdpYBDQSn",
"colab_type": "text"
},
"source": [
"Can you imagine having to write an **if** statement and print a different f-string each time you needed to do this greeting? Functions make it much easier and smarter to do actions like this in code!\n",
"\n",
"**Return values**\n",
"\n",
"As we've seen, functions are great for actions we need to repeat. We can use them to do something for us once or 100 times, depoinding on how many times we need it. Functions are also good at helping us perform calculations or make some changes to data before we can continue using it in our code. These kind of functions usually have ***return values***, which is the resulting output a function gives us back after calling it.\n",
"\n",
"We looked at the **range( )** function in the previous lessons. When we talked about loops, we used the **range( )** function to iterate through specific ranges of numbers. This function accepted a starting and stopping index (our input parameters). The **range( )** function then takes these parameters and create a list of all the numbers that are between these starting and stopping indices. The newly created list of numbers is then returned to us (our return value) so we can iterate through it in the loop we originally called it in.\n",
"\n",
"For example, to list the numbers from 0 to stopping index, we used:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "cVV35bMZGJGC",
"colab_type": "code",
"outputId": "9685c68b-c0d0-43b9-b4b0-ee76e4bdf584",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 102
}
},
"source": [
"for i in range(5):\n",
" print(i)"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"4\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lUqNVY9aG5Rk",
"colab_type": "text"
},
"source": [
"To list the numbers from starting index to stopping index, we used:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "cbqvXeoFF0UC",
"colab_type": "code",
"outputId": "98afcb8a-29d3-4b60-81f9-92dc2ac56807",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 85
}
},
"source": [
"for i in range(4,8):\n",
" print(i)"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"4\n",
"5\n",
"6\n",
"7\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "xs6uD2uKHOYu",
"colab_type": "text"
},
"source": [
"And to list the numbers from starting index to stopping index but by step amount, we used:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "exRg7ZTDHWr0",
"colab_type": "code",
"outputId": "09fa7b73-f4ec-4b39-96ee-fd8bf6344471",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 153
}
},
"source": [
"for i in range(4,20,2):\n",
" print(i)"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"4\n",
"6\n",
"8\n",
"10\n",
"12\n",
"14\n",
"16\n",
"18\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fOJlFLTCHhWI",
"colab_type": "text"
},
"source": [
"**Calling function**\n",
"\n",
"Calling a function is easy! Whenever there is a point in your code that you need to use a function, simply call it by writing the function name followed by parentheses():"
]
},
{
"cell_type": "code",
"metadata": {
"id": "-bxlZshzH2iI",
"colab_type": "code",
"outputId": "20a5a4fe-761e-43a7-9f81-552488fb1535",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"source": [
"greet(\"Jack\", False)"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"What's up, Jack? Nice to see you again!\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "x8Q0rtCNvVXP",
"colab_type": "text"
},
"source": [
"# **Resources**\n",
"\n",
"**Math Module**\n",
"\n",
"This is a built-in module that comes with the Python language. The **math module** provides functions that are ready for us to use and are commonly used in Python programming. As its name implies, this module provides many math functions, including **sum()**, **sqrt()**, and **pow()**.\n",
"\n",
"The **sum()** function accepts a list of integers as a parameter and returns the total of all the integers in the list. It's a ready-made function for adding.\n",
"\n",
"The **sqrt(x)** function accepts an integer and returns its square root. For example, **sqrt(81)** would return a value 9.\n",
"\n"
]
},
{
"cell_type": "code",
"metadata": {
"id": "fuZLo3xzxsid",
"colab_type": "code",
"colab": {}
},
"source": [
"from math import sqrt"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "Xu-p9vf9x-c_",
"colab_type": "code",
"outputId": "1c995624-c0df-4b29-bc2e-22aca59c6573",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"source": [
"sqrt(81)"
],
"execution_count": 0,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"9.0"
]
},
"metadata": {
"tags": []
},
"execution_count": 7
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MgVXFm1OxiUe",
"colab_type": "text"
},
"source": [
"The pow(x, y) function is another useful function that accepts two parameters and uses the exponentiation operator to return the x parameter to the y power. For example, using pow(3, 4) would return a value of 81."
]
},
{
"cell_type": "code",
"metadata": {
"id": "Ktx58pfOyc2I",
"colab_type": "code",
"colab": {}
},
"source": [
"from math import pow"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "BqJDKj6KyhIR",
"colab_type": "code",
"outputId": "54aa5135-6d98-46c4-f684-5f5816a897b5",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"source": [
"pow(3, 4)"
],
"execution_count": 0,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"81.0"
]
},
"metadata": {
"tags": []
},
"execution_count": 9
}
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "qeUfmUEkzVAn"
},
"source": [
"These functions are the most used ones in the math module, but there are many more. Go to Mathematical Functions in the Python Standard Library (https://docs.python.org/3/library/math.html) to see the full list."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "RvmrWwqKzcUQ",
"colab_type": "text"
},
"source": [
"**Random Module**\n",
"\n",
"Another built-in module that comes in handy for games and programs is the **random module**. As you can guess, it provides functions that help with the generation of random data. For our purpose, you can focus on the **randint()** functions from this module. Yes, \"randint\" stands for random integer!\n",
"\n",
"**randint(x, y)**: This function accepts two parameters: a starting number and an ending number. When you use this function, it picks a random number for you to use between the starting number and up to (but not including) the ending number. "
]
},
{
"cell_type": "code",
"metadata": {
"id": "_G4oYbD-0rqn",
"colab_type": "code",
"colab": {}
},
"source": [
"from random import randint"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "KuGx2K2h0zoq",
"colab_type": "code",
"outputId": "cd5fa615-6282-4533-a992-4c5b17690c70",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"source": [
"randint(0, 10)"
],
"execution_count": 0,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"7"
]
},
"metadata": {
"tags": []
},
"execution_count": 13
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "EeUEeDr906fg",
"colab_type": "text"
},
"source": [
"**Datetime Module**\n",
"\n",
"Another very useful module that is readily available in the Python language is called the **datetime module**. This module gives us many different functions to use that deal with time, dates, and changes to time and dates. \n",
"\n",
"The **now** function returns the current date and time.\n",
"The **timedelta** function allows to manipulate time according to the specific unit we set. \n",
"\n"
]
},
{
"cell_type": "code",
"metadata": {
"id": "upw8rQyn117O",
"colab_type": "code",
"outputId": "c0b84c32-9192-443a-c640-42fcc4301b77",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"source": [
"from datetime import datetime\n",
"current_time = datetime.now() \n",
"print(current_time)"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"2019-07-14 00:57:00.050569\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "K4sCLAxn1_PQ",
"colab_type": "code",
"outputId": "cd0919f9-1e3f-4d20-a652-b9054a823006",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"source": [
"from datetime import timedelta\n",
"NZ = current_time + timedelta(hours=9)\n",
"print(NZ)"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"2019-07-14 09:57:00.050569\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "U3G7eb4y_F7j",
"colab_type": "text"
},
"source": [
"Just like the math module, the datetime module offers so many other useful functions that can be useful in your programs. Be sure to check out the Basic Date and Time Types in the Python Standard LIbrary (https://docs.python.org/3/library/datetime.html) to see the full list."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "moFXXm6Eqoiq",
"colab_type": "text"
},
"source": [
"# **Activities**\n",
"\n",
"\n",
"1. Create a function called **superpower()**. Have your **superpower()** function accept two parameters: one called **name** and another called **power**. Using these parameters, have your function print out an f-string that says who you are and what your superpower is!\n",
"\n",
"> **Sample Expected Output:**\n",
"\n",
"\n",
"\n",
"```\n",
"'Hi, I'm Super Adrienne and my superpower is coding!''\n",
"```\n",
"\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"metadata": {
"id": "d6_ilXoPrrVj",
"colab_type": "code",
"colab": {}
},
"source": [
""
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "c_CZ9hn8rsUZ",
"colab_type": "text"
},
"source": [
"\n",
"2. One of the most common functions every coder has to write is called a ***factorial*** function. It's a function that calculates the factorial of the number you pass into it. And yes, it sounds like something to do with multiplication, because it is! In math, a factorial is the product of a number and all the numbers that come before it. So, if I ask you to calculate the factorial of the number 4, you would have to multiply 4 * 3 * 2 * 1. The factorial of 4 is 24.\n",
"\n",
"> Write a function called **factorial()** that takes one parameter. This parameter will be a number. Then, write the code to calculate the factorial of the number that is passed in as a parameter. Have your **factorial()** function return the answer!\n",
"\n",
"\n",
"\n",
"> **Sample Expected Output:**\n",
"\n",
"\n",
"```\n",
"factorial(4)\n",
"24\n",
"```\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"metadata": {
"id": "ABJZQ59XTp3G",
"colab_type": "code",
"colab": {}
},
"source": [
" "
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "HQOhBr5pelvM",
"colab_type": "code",
"outputId": "18e43efb-0e97-43dc-8e73-73b30d3f936a",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"source": [
"factorial(4)"
],
"execution_count": 0,
"outputs": [
{
"output_type": "stream",
"text": [
"24\n"
],
"name": "stdout"
}
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment