Functions: Code Recipes! 🍪📝
Write instructions once, use them again and again. Just like a recipe for your favorite cookies!
🤔 What is a Function?
A function is like a recipe. You write down the steps once, give it a name, and then you can use that recipe anytime!
Cookie Recipe = Function
📝 Write Recipe Once:
- Mix flour and sugar
- Add eggs and butter
- Add chocolate chips
- Bake at 350° for 12 min
🍪 Use Anytime!
Now whenever you want cookies, just say:
makeCookies() 🌍 Functions in Real Life
You use "functions" every day without realizing it!
"Take a Shower"
Many steps (get water, soap, rinse) but you just say "shower"!
"Press Start"
One button does LOTS of things to start the game!
"Call Mom"
Phone does many things with just two words!
⚙️ How Functions Work
Making a function has two parts:
Create (Define) the Function
Write down all the steps and give it a name:
function sayHello ()
print "Hello there!"
print "Nice to meet you!"
Call (Use) the Function
Just say its name to make it run!
sayHello () // This runs all the steps! Output:
Hello there!
Nice to meet you!
🎁 Functions Can Take Inputs!
You can give information TO a function, like putting ingredients into a recipe!
🍕 Pizza Function
function makePizza ( topping )
print "Making pizza with"
print topping
🎉 Using It!
makePizza("pepperoni") → Making pizza with pepperoni
makePizza("cheese") → Making pizza with cheese
makePizza("veggies") → Making pizza with veggies
🎁 Functions Can Give Back Results!
Some functions give you something back, like a vending machine giving you a snack!
Put in: 2 + 3
add(2, 3) Function does math
Get back: 5
🎮 Functions in Games!
Video games are FULL of functions!
attack()
Swing sword, play sound, deal damage - all in one function!
jump()
Make character go up, play whoosh sound, then come back down!
collectCoin()
Add to score, make coin disappear, play cha-ching!
gameOver()
Stop game, show score, ask to play again!
💪 Why Are Functions Awesome?
Stay Organized
Keep related code together in neat packages!
Reuse Code
Write once, use many times!
Fix Bugs Easier
Fix in one place, works everywhere!
Work Together
Teams can share and use each other's functions!
⭐ Remember This!
- 1
Functions are like recipes - write steps once, use anytime!
- 2
Give your function a name that describes what it does
- 3
Functions can take inputs (like ingredients)
- 4
Functions can give back results (like a vending machine)