Python Functions: A Named Set of Instructions

Understand Python: LESSON 14 FUNCTIONS IN PYTHON ■ First, What Is a Function? A function is a named set of instructions that tells Python how to perform a specific task. Think of it like this: 👉 A function is a machine, You give it a job, it does a job and gives you a result ▪︎ Let's use a real-life analogy. 👉 Imagine you have a juice machine. You put in oranges, you press a button, and the machine makes orange juice You don’t need to know how the machine works inside. You just use it. That’s exactly how a function works. ■ Why Do We Need Functions? Without functions, we tend to always repeat ourselves. > Example without a function: print("Welcome Ben") print("Welcome Ben") print("Welcome Ben") That’s boring and messy. > With a function: def greet(): print("Welcome Ben") We can now print as many "Welcome Ben" messages as we like by simply calling the great function. 👇 greet() greet() greet() Now the work is clean and organized. ■ Functions help us: • Avoid repeating code • Keep code neat • It makes programs easier to understand ■ The Basic Shape of a Function Every function has three parts: 1. The keyword def 2. The function name 3. The instructions inside it 👇 def say_hello(): print("Hello!") Let’s read this in English: “Python, define a function called say_hello that prints Hello.” ■ Calling a Function Creating a function is not enough. You must call it to make it run. say_hello() Think of it like: If you just write a recipe, it doesn't cook a food. You must use the recipe. Let's consider the following examples. Example 1: A Function That Prints a Welcome Message def welcome(): print("Welcome to Python") Calling it: > welcome() Example 2: A Function That Prints Numbers 1 to 5 def print_numbers(): for i in range(1, 6): print(i) Calling it: > print_numbers() #python

  • No alternative text description for this image

Learning Python as a beginner doesn’t have to be confusing. I share simple, structured Python lessons and coding tips on my YouTube channel for people starting out in tech. 🎥 Subscribe here: https://youtube.com/@tonybenard7210?si=8R6opV3kZ_HDR242

Like
Reply

To view or add a comment, sign in

Explore content categories