You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1135 lines
28 KiB

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

{
"cells": [
{
"cell_type": "markdown",
"id": "ceramic-hygiene",
"metadata": {},
"source": [
"<!--\n",
"title: Python Programming: Functions\n",
"type: lesson\n",
"duration: \"01:00\"\n",
"creator: Susi Remondi\n",
"-->\n",
"\n",
"\n",
"<h1>Python Programming: Functions</h1>\n",
"\n",
"\n",
"<!--\n",
"\n",
"## Overview\n",
"This lesson introduces students to the concept of functions, beginning with regular functions, then parameters, then multiple parameters. It continues with returning values from functions. It ends with a series of You Do exercises.\n",
"\n",
"## Learning Objectives\n",
"In this lesson, students will:\n",
"- Identify when to use a function.\n",
"- Create and call a function with arguments.\n",
"- Return a value from a function.\n",
"\n",
"## Duration\n",
"90 minutes\n",
"\n",
"### Note on timing:\n",
"This functions lesson is designed to roll into the next one; it ends at a logical break to account for the class timing, but they go together.\n",
"\n",
"In the 5 day class, this means that the overall function lessons are designed to roll and continue in the next class. The homework doesn't have parameters, so if you don't get there, that's fine. Go as far as you can until the day is over, then pick up where you left off the next class. This lesson ends with a series of You Do exercises. **Student understanding is more important than staying within the timeframe** - the next lesson is flexible with many exercises that can be dropped.\n",
"\n",
"\n",
"## Suggested Agenda\n",
"\n",
"| Time | Activity |\n",
"| --- | --- |\n",
"| 0:00 - 0:03 | Welcome |\n",
"| 0:03 - 0:18| Basic Functions |\n",
"| 0:20 - 0:35 | Parameters |\n",
"| 0:35 - 0:57 | Returns and Exercises |\n",
"| 0:57 - 0:60 | Summary |\n",
"\n",
"## In Class: Materials\n",
"- Projector\n",
"- Internet connection\n",
"- Python3\n",
"-->\n",
"\n",
"---\n",
"\n",
"## Learning Objectives\n",
"*After this lesson, you will be able to...*\n",
"\n",
"- Identify when to use a function.\n",
"- Create and call a function with arguments.\n",
"- Return a value from a function.\n",
"\n",
"---\n",
"\n",
"## Let's Consider a Repetitive program...\n",
"\n",
"Consider a program that prints a $5 shipping charge for products on a website:\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "strange-auction",
"metadata": {},
"outputs": [],
"source": [
"print(\"You've purchased a Hanging Planter.\")\n",
"print(\"Thank you for your order. There will be a $5.00 shipping charge for this order.\")\n",
"\n",
"# 10 minutes later...\n",
"print(\"You've purchased a Shell Mirror.\")\n",
"print(\"Thank you for your order. There will be a $5.00 shipping charge for this order.\")\n",
"\n",
"# 5 minutes later...\n",
"print(\"You've purchased a Modern Shag Rug.\")\n",
"print(\"Thank you for your order. There will be a $5.00 shipping charge for this order.\")"
]
},
{
"cell_type": "markdown",
"id": "mediterranean-amount",
"metadata": {},
"source": [
"\n",
"What if there are 1,000 orders?\n",
"\n",
"---\n",
"\n",
"## Functions\n",
"\n",
"We can write a **function** to print the order.\n",
"\n",
"A function is simpleit's a reusable piece of code. We only define it once. Later, we can use its name as a shortcut to run that whole chunk of code.\n",
"\n",
"* Functions are defined using the `def` syntax.\n",
" * `def` stands for \"define.\"\n",
"* In this case, we're *defining* a function named 'function_name.'\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "daily-noise",
"metadata": {},
"outputs": [],
"source": [
"def function_name():\n",
" # What you want the function to do\n",
" pass\n",
"\n",
"# Call the function by name to run it:\n",
"function_name()\n",
"\n",
"# 10 minutes later...\n",
"function_name()"
]
},
{
"cell_type": "markdown",
"id": "annoying-things",
"metadata": {},
"source": [
"\n",
"**Protip:** Don't forget the `()`, and be sure to indent!\n",
"\n",
"---\n",
"\n",
"## Seeing Functions in Action\n",
"\n",
"So we *define* the function, then we can *call* the function by pairing its name with the parentheses: `print_order()`."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "manufactured-boutique",
"metadata": {},
"outputs": [],
"source": [
"def print_order():\n",
" print(\"Thank you for your order. There will be a $5.00 shipping charge for this order.\")\n",
"\n",
"print(\"You've purchased a Hanging Planter.\")\n",
"print_order()"
]
},
{
"cell_type": "markdown",
"id": "supposed-alabama",
"metadata": {},
"source": [
"\n",
"</aside>\n",
"\n",
"---\n",
"\n",
"## Naming a Function\n",
"\n",
"What can you name a function?\n",
"- Anything you'd like.\n",
" - But match the intention and the *invocation*!\n",
"- Using `print_order` is more descriptive.\n",
"\n",
"What do you think will happen if you change the function name `print_order` to `finishedOrder` without updating the invocation?"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "attended-friendship",
"metadata": {},
"outputs": [],
"source": [
"del print_order\n",
"\n",
"def finished_order():\n",
" print(\"Thank you for your order. There will be a $5.00 shipping charge for this order.\")\n",
" \n",
"print(\"You've purchased a Hanging Planter.\")\n",
"print_order()\n"
]
},
{
"cell_type": "markdown",
"id": "suspended-failure",
"metadata": {},
"source": [
"\n",
"</aside>\n",
"\n",
"---\n",
"\n",
"## Multi-Line Functions\n",
"\n",
"\n",
"How many lines of code can a function have?\n",
"- As many lines of code as you'd like!\n",
"- Just indent each line.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "gorgeous-failure",
"metadata": {},
"outputs": [],
"source": [
"def welcome():\n",
" print(\"Hello!\")\n",
" print(\"Bonjour!\")\n",
"\n",
"welcome()"
]
},
{
"cell_type": "markdown",
"id": "attached-publicity",
"metadata": {},
"source": [
"\n",
"---\n",
"\n",
"## We Do: Writing a Function\n",
"\n",
"Let's make this a little more complicated.\n",
"\n",
"Let's write a function together, `high_low`, that prints \"High!\" if a variable `my_number` is greater than 10 and \"Low!\" if it isn't."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "italian-statistics",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"id": "governmental-conclusion",
"metadata": {},
"source": [
"\n",
"</aside>\n",
"\n",
"---\n",
"\n",
"## You Do: FizzBuzz\n",
"\n",
"This is a *very* common programming question. It's often on job interviews and a buzzword in the industry as a simple but common task to show your understanding.\n",
"\n",
"- Write a function that prints the numbers from 1 to 101.\n",
"- But, for multiples of three, print “Fizz” instead of the number.\n",
"- For multiples of five, print “Buzz”.\n",
"- For numbers which are multiples of both three and five, print “FizzBuzz”.\n",
"- Don't forget to call the function!\n",
"\n",
"_Hint: think carefully about the order of your conditionals._"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "blessed-happiness",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"id": "banner-conclusion",
"metadata": {},
"source": [
"\n",
"</aside>\n",
"\n",
"---\n",
"\n",
"## Quick Review: Functions\n",
"\n",
"Functions are reusable chunks of code. They can have anything in them.\n",
"\n",
"* Define functions using the `def` keyword.\n",
"* A function must be **called** before the code in it will run!\n",
"* You will recognize function calls by the `()` at the end.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "balanced-force",
"metadata": {},
"outputs": [],
"source": [
"# This part is the function definition!\n",
"def say_hello():\n",
" print(\"hello world!\")\n",
"\n",
"# This part is actually calling/running the function!\n",
"say_hello()\n"
]
},
{
"cell_type": "markdown",
"id": "premier-stomach",
"metadata": {},
"source": [
"\n",
"You can call them as many times as you'd like, but they need to be defined above the code where you call them.\n",
"\n",
"Up next: Parameters!\n",
"\n",
"---\n",
"\n",
"\n",
"## Discussion: Parameters\n",
"\n",
"\n",
"Remember this?\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "adjustable-permit",
"metadata": {},
"outputs": [],
"source": [
"def print_order():\n",
" print(\"Thank you for your order. There will be a $5.00 shipping charge for this order.\")\n",
"\n",
"print(\"You've purchased a Hanging Planter.\")\n",
"print_order()\n",
"\n",
"print(\"You've purchased a Shell Mirror.\")\n",
"print_order()\n",
"\n",
"print(\"You've purchased a Modern Shag Rug.\")\n",
"print_order()"
]
},
{
"cell_type": "markdown",
"id": "nominated-anime",
"metadata": {},
"source": [
"\n",
"There's still repetition. How do you think we could improve it?\n",
"\n",
"---\n",
"\n",
"## Addressing the repetition\n",
"\n",
"We can dynamically pass a function values. This is a **parameter**.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "loved-arthur",
"metadata": {},
"outputs": [],
"source": [
"def print_order(product):\n",
" print(f\"Thank you for ordering the {product}.\")\n",
"\n",
"print_order(\"Hanging Planter\")\n",
"# Prints \"Thank you for ordering the Hanging Planter.\"\n",
"print_order(\"Shell Mirror\")\n",
"# Prints \"Thank you for ordering the Shell Mirror.\"\n",
"print_order(\"Modern Shag Rug\")\n",
"# Prints \"Thank you for ordering the Modern Shag Rug.\""
]
},
{
"cell_type": "markdown",
"id": "several-suspension",
"metadata": {},
"source": [
"\n",
"<aside class=\"notes\">\n",
"\n",
"---\n",
"\n",
"## Terminology Recap\n",
"\n",
"**Parameter:** The variable that's defined in a function's declaration.\n",
"\n",
"**Argument:** The actual value passed into the function when the function is called.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "creative-hardwood",
"metadata": {},
"outputs": [],
"source": [
"def my_function(parameter):\n",
" # Does something.\n",
"\n",
"my_function(argument)"
]
},
{
"cell_type": "markdown",
"id": "owned-soldier",
"metadata": {},
"source": [
"\n",
"---\n",
"\n",
"## Case of the Missing Argument\n",
"\n",
"\n",
"What happens if you do this incorrectly?\n",
"\n",
"Try removing `\"Hanging Planter\"` from the code so `print_order` is called with an empty parentheses."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "personalized-split",
"metadata": {},
"outputs": [],
"source": [
"def print_order(product):\n",
" print(\"Thank you for ordering the\", product, \".\")\n",
" print(\"There will be a $5.00 shipping charge for this order.\")\n",
"\n",
"print_order(\"Hanging Planter\")\n",
"print_order(\"Shell Mirror\")\n",
"print_order(\"Modern Shag Rug\")"
]
},
{
"cell_type": "markdown",
"id": "hybrid-cancellation",
"metadata": {},
"source": [
"\n",
"---\n",
"\n",
"## Partner Exercise: Thanks a Latte\n",
"\n",
"\n",
"Pair up! Decide who will be the driver and who will be the navigator.\n",
"\n",
"Imagine that you are tasked with creating a program to calculate the total amount, including sales tax, for each item at a coffee shop.\n",
"\n",
"---\n",
"\n",
"## Partner Exercise: Thanks a Latte\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "governmental-collection",
"metadata": {},
"outputs": [],
"source": [
"def latte_total():\n",
" price = 5.50\n",
" sales_tax_rate = .10\n",
" total_amount = price + (price * sales_tax_rate)\n",
" print(\"The total is $\", total_amount)\n",
"\n",
"latte_total()\n",
"\n",
"def americano_total():\n",
" price = 4.75\n",
" sales_tax_rate = .10\n",
" total_amount = price + (price * sales_tax_rate)\n",
" print(\"The total is $\", total_amount)\n",
"\n",
"americano_total()"
]
},
{
"cell_type": "markdown",
"id": "basic-democracy",
"metadata": {},
"source": [
"\n",
"---\n",
"\n",
"## Keep it DRY (Don't Repeat Yourself)\n",
"\n",
"But what if we have several drinks at the coffee shop?\n",
"\n",
"- With your partner, create a function called `calculate_price` that accepts one parameter `price`, the price of a drink, and prints the total with sales tax included.\n",
"- Call your function with arguments `5.5` (the latte) and `4.75` (the americano). "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "front-overview",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"id": "preceding-script",
"metadata": {},
"source": [
"\n",
"---\n",
"\n",
"## Multiple Parameters: Part 1\n",
"\n",
"What about changing sales tax? We can pass as many values into the function as we want - we can have as many parameters as we want.\n",
"\n",
"Here, we have a second parameter, `taxes`:\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "sought-kingdom",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"id": "practical-paris",
"metadata": {},
"source": [
"\n",
"**Protip:** Use a comma-separated list — (parameter1, parameter2, parameter3, parameter4)\n",
"\n",
"---\n",
"\n",
"## Multiple Parameters: Part 2\n",
"\n",
"With parameters, order matters! Programs don't automatically understand what should go where - they assign values in order."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "experienced-hazard",
"metadata": {},
"outputs": [],
"source": [
"def greet_user(firstName, lastName, year, city):\n",
" print(\"Hello\", firstName, lastName, \"born in\", year, \"from\", city, \"!\")\n",
"\n",
"greet_user(\"Bruce\", \"Wayne\", 1939, \"Gotham\")\n",
"greet_user(\"Bruce\", 1939, \"Gotham\", \"Wayne\")"
]
},
{
"cell_type": "markdown",
"id": "demanding-fifty",
"metadata": {},
"source": [
"\n",
"---\n",
"\n",
"## Partner Exercise: Functions With Logic\n",
"\n",
"\n",
"With the same partner, switch drivers.\n",
"\n",
"Let's go back to our shipping example. Depending on the order amount, our user might get free shipping, so the print statement is different.\n",
"\n",
"Use this starter code, which works for one product. Can you build a function from it that works for any `product` and `order_amount`?\n",
"\n",
"Test your code with the following products and prices:\n",
"- Hanging Planter - 35\n",
"- Shell Mirror - 15\n",
"- Modern Shag Rug - 75"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "nasty-coupon",
"metadata": {},
"outputs": [],
"source": [
"product = \"Hanging Planter\"\n",
"order_amount = 35\n",
"\n",
"print(\"Thank you for ordering the Hanging Planter.\")\n",
"if order_amount >= 30:\n",
" print(\"It's your lucky day! There is no shipping charge for orders over $30.00.\")\n",
"else:\n",
" print(\"There will be a $5.00 shipping charge for this order.\")\n"
]
},
{
"cell_type": "markdown",
"id": "satisfied-unknown",
"metadata": {},
"source": [
"\n",
"* **Hint:** You can put any code you'd like inside a function.\n",
"* **Reminder:** Don't forget to indent!"
]
},
{
"cell_type": "markdown",
"id": "bizarre-holder",
"metadata": {},
"source": [
"\n",
"</aside>\n",
"\n",
"---\n",
"\n",
"## Quick Review: Functions with Parameters\n",
"\n",
"**Parameter:** The variable that's defined in a function's declaration.\n",
"\n",
"**Argument:** The actual value passed into the function when the function is called.\n",
"\n",
"Order matters!\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "broke-shield",
"metadata": {},
"outputs": [],
"source": [
"def do_something(parameter1, parameter2):\n",
" # Does something.\n",
"\n",
"do_something(argument1, argument2)\n",
"do_something(a_different_a"
]
},
{
"cell_type": "markdown",
"id": "polar-confusion",
"metadata": {},
"source": [
"\n",
"Next up: Returns.\n",
"\n",
"---\n",
"\n",
"## The Return\n",
"\n",
"Sometimes, we want values *back* from functions.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "tender-cache",
"metadata": {},
"outputs": [],
"source": [
"def calculate_total(price, taxes):\n",
" total_amount = price + (price * taxes)\n",
" print('The total is $', total_amount)\n",
" # Send the total_amount for the drink back to the main program.\n",
" return total_amount\n",
"\n",
"# This just calls the function - we've seen this.\n",
"calculate_total(5.5, .10)\n",
"\n",
"# This is new! Save the amount of this drink into a variable \"latte_total.\"\n",
"latte_total = calculate_total(5.5, .10)\n",
"\n",
"# Now, we can use that variable.\n",
"print('Your order total is', latte_total)"
]
},
{
"cell_type": "markdown",
"id": "muslim-austria",
"metadata": {},
"source": [
"\n",
"* `total_amount` is returned to the main program.\n",
"\n",
"* The value in `total_amount` is saved as `latte_total`.\n",
"\n",
"* When we **return** something, it ends the function's execution and \"spits out\" whatever we are returning.\n",
"\n",
"---\n",
"\n",
"## We Do: Practicing Returns\n",
"\n",
"Let's fill this in together:\n",
"\n",
"- Define a function, `add_two`, that takes a parameter `number`.\n",
"- It adds `2` to `number`, saving that in a new variable, `total`; print `total` out. Then, return `total`."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "twenty-christmas",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"id": "unlimited-guard",
"metadata": {},
"source": [
"\n",
"---\n",
"\n",
"## Discussion: Return Statements With Logic\n",
"\n",
"The `return` statement *exits a function*, not executing any further code in it. What do you think the following will print?\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "coordinated-calgary",
"metadata": {},
"outputs": [],
"source": [
"def mystery():\n",
" return 6\n",
" return 5\n",
"\n",
"my_number = mystery()\n",
"print(my_number)"
]
},
{
"cell_type": "markdown",
"id": "removable-creek",
"metadata": {},
"source": [
"\n",
"---\n",
"\n",
"## Discussion: What Will Happen?\n",
"\n",
"What do you think will print out?\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "alleged-transport",
"metadata": {},
"outputs": [],
"source": [
"def add_bonus_points(score):\n",
" if score > 50:\n",
" return score + 10\n",
" score += 20\n",
" return score\n",
"\n",
"total_points = add_bonus_points(55)\n",
"print(total_points)"
]
},
{
"cell_type": "markdown",
"id": "bored-break",
"metadata": {},
"source": [
"\n",
"---\n",
"\n",
"## Exiting a Function\n",
"\n",
"\n",
"We can also use `return` by itself as a way to exit the function and prevent any code that follows from running.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "painful-wholesale",
"metadata": {},
"outputs": [],
"source": [
"def rock_and_roll(muted):\n",
" song = \"It's only Rock 'N' Roll\"\n",
" artist = \"Rolling Stones\"\n",
"\n",
" if (muted == True):\n",
" return\n",
" # Here, we use return as a way to exit a function\n",
" # We don't actually return any value.\n",
" print(\"Now playing: \", song, \" by \", artist)\n",
"\n",
"rock_and_roll(True)"
]
},
{
"cell_type": "markdown",
"id": "instrumental-baking",
"metadata": {},
"source": [
"\n",
"---\n",
"\n",
"## Quick Knowledge Check\n",
"\n",
"Looking at this code, where will the function stop if `x` is `10`?\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "educational-burton",
"metadata": {},
"outputs": [],
"source": [
"def categorize(x):\n",
" if (x < 8):\n",
" return 8\n",
" x += 3\n",
" if (x < 15):\n",
" return x\n",
" return 100\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "characteristic-simon",
"metadata": {},
"source": [
"\n",
"---\n",
"\n",
"## Another Knowledge Check\n",
"\n",
"Take this simple `adder` function:\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "biological-evaluation",
"metadata": {},
"outputs": [],
"source": [
"def adder(number1, number2):\n",
" return number1 + number2\n"
]
},
{
"cell_type": "markdown",
"id": "acting-venue",
"metadata": {},
"source": [
"\n",
"Which of the following statements will result in an error?\n",
"\n",
"A. `adder(10, 100.)` <br>\n",
"B. `adder(10, '10')` <br>\n",
"C. `adder(100)` <br>\n",
"D. `adder('abc', 'def')` <br>\n",
"E. `adder(10, 20, 30)` <br>\n",
"\n",
"---\n",
"\n",
"## Quick Review: Return Statements\n",
"\n",
"Return statements allow us to get values back from functions:\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "still-introduction",
"metadata": {},
"outputs": [],
"source": [
"def add_two(number):\n",
" total = number + 2\n",
" print(total)\n",
" return total\n",
"\n",
"final_var = add_two(3)\n",
"print(final_var)"
]
},
{
"cell_type": "markdown",
"id": "breeding-technology",
"metadata": {},
"source": [
"\n",
"Return statements also exit the function - no further code in the function happens!\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "quarterly-terrain",
"metadata": {},
"outputs": [],
"source": [
"def add_bonus_points(score):\n",
" if score > 50:\n",
" return score + 10\n",
" score += 30\n",
" return score\n",
"\n",
"total_points = add_bonus_points(55)\n",
"print(total_points) # 65\n",
"total_points = add_bonus_points(10)\n",
"print(total_points) # 40"
]
},
{
"cell_type": "markdown",
"id": "aerial-reasoning",
"metadata": {},
"source": [
"\n",
"---\n",
"\n",
"## Temperature Conversion\n",
"\n",
"When we were learning about conditionals, we took a look at a program that let us know if it was too hot or too cold:\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "derived-armor",
"metadata": {},
"outputs": [],
"source": [
"temperature = 308\n",
"if temperature > 299:\n",
" print(\"It's too hot!\")\n",
"elif temperature <= 299 and temperature > 288:\n",
" print(\"It's just right!\")\n",
"elif temperature <= 288 and temperature > 277:\n",
" print(\"It's pretty cold!\")\n",
"else:\n",
" print(\"It's freezing!\")"
]
},
{
"cell_type": "markdown",
"id": "micro-municipality",
"metadata": {},
"source": [
"\n",
"That's good logic, but Kelvins aren't incredibly useful on a day-to-day basis, unless you're a scientist. Let's use a function to convert temperatures.\n",
"\n",
"---\n",
"\n",
"## You Do: Temperature Conversion\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "textile-being",
"metadata": {},
"source": [
"\n",
"Here are the formulas to use:\n",
"\n",
"* **Celsius to Kelvin** : `K = °C + 273`\n",
"* **Fahrenheit to Kelvin** : `K = (5/9) * (°F - 32) + 273`\n",
"\n",
"Try to use one function to convert from either Fahrenheit or Celsius based upon a second parameter."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "united-blair",
"metadata": {},
"outputs": [],
"source": [
"# create your function here\n",
"\n",
"\n",
"# convert a temperature in either 'F' or 'C' into Kelvins using your function\n",
"# store the result in a variable called 'temperature'\n",
"# try out some different values and temperature scales\n",
"\n",
"\n",
"if temperature > 299:\n",
" print(\"It's too hot!\")\n",
"elif temperature <= 299 and temperature > 288:\n",
" print(\"It's just right!\")\n",
"elif temperature <= 288 and temperature > 277:\n",
" print(\"It's pretty cold!\")\n",
"else:\n",
" print(\"It's freezing!\")"
]
},
{
"cell_type": "markdown",
"id": "nutritional-insight",
"metadata": {},
"source": [
"\n",
"---\n",
"\n",
"## Exercise: Building a Copy\n",
"\n",
"Write a function, `copy_list`, that takes in a list, `original_list`, as a parameter. Your function should create a new list, `my_new_list` with the contents of the original list. Your function should return `my_new_list`."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "forced-cocktail",
"metadata": {},
"outputs": [],
"source": [
"# function defenition\n",
"\n",
"\n",
"\n",
"\n",
"my_list = [1, 2, 3]\n",
"my_new_list = copy_list(my_list)\n",
"print(my_new_list)\n",
"# Will print [1, 2, 3]"
]
},
{
"cell_type": "markdown",
"id": "surgical-genesis",
"metadata": {},
"source": [
"\n",
"---\n",
"\n",
"## Exercise: Reversing a List\n",
"\n",
"Write a function, `reverse_list`, that takes in a list, `my_list`, as a parameter. Your function should reverse the list and return it."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "needed-biodiversity",
"metadata": {},
"outputs": [],
"source": [
"# function defenition\n",
"\n",
"\n",
"\n",
"my_list = [1, 2, 3]\n",
"reversed_list = reverse_list(my_list)\n",
"print(reversed_list)\n",
"# Will print [3, 2, 1]"
]
},
{
"cell_type": "markdown",
"id": "yellow-handbook",
"metadata": {},
"source": [
"\n",
"---\n",
"\n",
"## Summary + Q&A:\n",
"\n",
"Can you now:\n",
"\n",
"- Identify when to use a function?\n",
"- Create and call a function with arguments?\n",
"- Return a value from a function?"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}