w1coding.comAll tutorials

Python Functions

Python lessons
  1. Environment Setup
  2. Introduction
  3. Control
  4. Control
  5. Loops
  6. Functions
  7. Lists
  8. Dictionary
  9. Classes
  10. Exception
  11. File
  12. Libray
  13. Date
  14. Regula
  15. JSON
  16. Web
  17. Zweb
  18. Apis
  19. Unity
  20. Llampda
  21. Iterators
  22. Generators
  23. Files
  24. Context
  25. Ilogging
  26. Multithreading
  27. Networking
  28. SQLite

Python Functions

Functions allow you to group code into reusable blocks. Functions in Python are defined using the def keyword.

Defining a Function

Here's how to define and call a function:

      
        def greet(name):
            print("Hello, " + name + "!")
        
        greet("Alice")
      
    

This function takes one argument, name, and prints a greeting.

Returning Values

Functions can return values using the return keyword:

      
        def add(x, y):
            return x + y
        
        result = add(5, 3)
        print(result)
      
    

This function returns the sum of x and y.

Activity

Try It Yourself!

Create a function that takes a number as an argument and returns its square.

Quick Quiz

Quick Quiz

  1. What keyword is used to define a function in Python?
  2. What does the return keyword do in a function?

Answers: Use def to define a function. The return keyword is used to return a value from a function.