It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

Intro to Functions

Functions are blocks of reusable code that help us organize our programs, avoid repetition, and make our code cleaner and easier to understand.

What Is a Function?

Think of a function as a machine: You give it some input (called arguments), and it gives you back an output (called the return value). A function can also do something internally without returning anything.

In Python, you define a function using the def keyword, followed by the function name and parentheses ().

def say_hello():
    print("Hello, world!")

This code defines a function called say_hello. But defining a function does not run it. You have to call it:

say_hello()  # Output: Hello, world!

Why Use Functions?

  • Reduce repetition in your code
  • Break down complex problems into smaller pieces
  • Make your code easier to test and debug
  • Improve readability and collaboration

Anatomy of a Function

Here’s a function that accepts input:

def greet(name):
    print(f"Hello, {name}!")

Then, call it(use it) like this:

greet("Alice")  # Output: Hello, Alice!
greet("Bob")    # Output: Hello, Bob!

Parameters vs Arguments

  • Parameter is the variable used in the function definition: name in the example above.
  • Argument is the actual value passed when calling the function: "Alice" or "Bob".

Summary

  • Functions are reusable blocks of code.
  • You define them using def.
  • Use them to avoid repetition and improve clarity.
  • You can pass values into them using parameters.

Exercise: Try It Yourself!

  1. Create a function called welcome() that prints "Welcome to LanceCourse!".
  2. Create a function called square_number() that accepts a number and prints its square.
  3. Create a function describe_pet() that takes a pet name and type, then prints a sentence like "My dog is called Rex."