PedroGeoGISdev
  • Home
  • Linux OS
    • Linux: concepts
    • Linux: basic concepts
    • Linux: Bash
    • Linux: su and sudo
    • Linux: pipes
    • Linux: File System
    • Linux: Virtual Machines

    • Linux: distros
    • Linux Distros: Ubuntu
    • Linux Distros: Mint
    • Linux Distros: Debian
    • Linux Distros: openSuse
    • Linux Distros: Manjaro
    • Linux Distros: Red Hat Enterprise

    • Linux: laboratories
    • Linux Lab#LI01-1: Choose Linux
    • Linux Lab#LI01-2: Install at least three distributions
    • Linux Lab#LI01-3: Adjust user permissions
    • Linux Lab#LI02-1: Export env user with grep and pipe
    • Linux Lab#LI03-1: Manage users and groups
    • Linux Lab#LI03-2: Manage files
    • Linux Lab#LI03-3: Manage software
    • Linux Lab#LI03-4: Manage hardware
    • Linux Lab#LI04-1: Bash scripting, qtool
    • Linux Lab#LI04-2: Bash scripts as terminal tool
    • Linux Lab#LI04-3: Distribute the terminal app

    • Linux readings
    • Linux Resources
  • DevOps
    • What is DevOps
    • DevOps: Introduction
    • DevOps: Agile and Microservices
    • Infrastructure as code (IaC)
    • Immutable Infrastructure
    • Software Lifecycle

    • Documentation
    • How to document: Quarto and Obsidian

    • Network protocols
    • Network: Basics
    • Network: Client-server
    • Network Protocols
    • Network: DNS
    • Network: API Rest
    • Network: gRPC
    • Network: Websocket
    • Network: SMTP
    • Network: Ping
    • Network: UDP
    • Network: webhook
    • Network: SOAP
    • Network: graphQL

    • Version Control
    • Git
    • GitHub
    • Idea and GitHub 2023
    • Git and GitHub 2023 CLI

    • IDEs
    • IDE: Visual Code
    • IDE: IntellJIdea

    • DevOps tools
    • Amazon Web Services AWS
    • Docker
    • Jenkins pipelines
    • Kubernetes k8s
    • Digital Ocean
    • Nagios
    • Ansible

    • DevOps Laboratories
    • Lab 1: chat App
    • Lab 2: Spring Boot AWS AEB manually
    • Lab 3: Spring Boot and AWS S3 publisher
    • Lab 4: Spring Boot Docker/Jenkins
    • Lab 5: k8s on Digital Ocean
    • Lab 6: Spring Boot AWS codecommit

    • DevOps readings
    • DevOps Resources
  • MarkUp
    • MarkUp Languages
    • Introduction Markup
    • HTML Markup
    • Markdown Markup
    • Markdown and HTML working together, good idea?

    • Quarto Markdown
    • Quarto Markdown: basics
    • Quarto Markdown: creating
    • Quarto Markdown: publishing
    • Quarto Markdown: code & data
    • Quarto Markdown: api rest call
    • Quarto Markdown: OJS Cells
    • Quarto Markdown: cheat-sheet

    • Styling: CSS
    • Cascade Style Sheet
    • Cascade Style Sheet: Box Model and Containers
    • CSS: W3.css

    • MarkUp Languages Laboratories
    • Lab#MD01-1: Create and publish by Quarto

    • MarkUp Languages readings
    • MarkUp Languages Resources
  • Java SE
    • What is Java SE
    • Java Standard Edition: Basics
    • Java Standard Edition: Principles
    • Java MOOC Helsinki
    • Java MOOC Helsinki Syllabus

    • Java Create Project
    • Java SE: Maven
    • Java SE: Create Maven Project
    • Java SE: Project push GitHub
    • Java SE: JUnit and TDD

    • Java Concepts
    • Java SE: Class and Objects
    • Java SE: Scope
    • Java SE: static modifier
    • Java SE: Coupling and DDD
    • Java SE: Packages
    • Java SE: Abstract/Interface
    • Java SE: Java 8

    • Java Principles
    • Java SE: Encapsulation
    • Java SE: Abstraction
    • Java SE: Inherence
    • Java SE: Polymorphism

    • Java Design Patterns
    • Java Patterns: UML
    • Java Patterns: Types
    • Singleton
    • Factory
    • Abstract Factory
    • Builder
    • Facade
    • Bridge
    • Decorator
    • Composite
    • Observer
    • Strategy
    • State
    • Commander

    • Java SE Laboratories
    • Lab#SE00-1: Maven Person
    • Lab#SE00-2: Maven Clinic
    • Lab#SE00-3: Library Model
    • Lab#SE00-4: Abstract/Interface Human
    • Lab#SE01-1: Maven/Gradle Person and Account
    • Lab#SE01-2: Maven/Gradle Person and Account stored in JSON
    • Lab#SE02-1: Movie/Review, Model
    • Lab#SE02-2: Movie/Review, CRUD Operations
    • Lab#SE02-3: Movie/Review, factory
    • Lab#SE02-4: Movie/Review, interactivity and coupling
    • Lab#SE02-5: Movie/Review, simulate interactivity by console
    • Lab#SE03-1: Library/Book, Core-Model
    • Lab#SE03-2: Library/Book, Sprint Zero
    • Lab#SE03-3: Library/Book, Expand Model
    • Lab#SE04-1: healthyFood Restaurant, Core Model

    • Java SE readings
    • Java SE Resources
  • Python
    • Python Basics
    • Python: Basic Concepts
    • Python: Numbers
    • Python: Strings
    • Python: Conditionals
    • Python: Lists and Loops
    • Python: Nested Loops
    • Python: Tuples
    • Python: Sets
    • Python: Dictionaries
    • Python: Functions
    • Python: Higher-order Functions
    • Python: Variable Scope
    • Python: Variable Assigment
    • Python: None keyword in Python
    • Python: Object Oriented Programming (OOP)
    • Python: Inheritance and Polymorphism
    • Python: Encapsulation
    • Python: Abstraction
    • Python: Exceptions
    • Python: Cheat-Sheets
  • JavaScript
    • JavaScript Basics
    • JavaScript: Fundamentals
    • JavaScript: Data Types
    • JavaScript: Variables
    • JavaScript: Operators
    • JavaScript: Conditionals
    • JavaScript: Loops
    • JavaScript: Functions
    • JavaScript: Arrays
    • JavaScript: Objects

    • React Framework

    • ReactJS: Principles
    • React JS: Introduction
    • React JS: render virtual DOM
    • React JS: Create a React project
    • React JS: Components
    • React JS: JSX
    • React JS: props and state

    • JavaScript: web scripting
    • JavaScript: basics
    • JavaScript: functions
    • JavaScript: objects
    • JavaScript: variables
    • JavaScript: flux control

    • ES6: ECMAScript 6
    • React JS ES6: arrow functions
    • React JS ES6: import modules
    • React JS ES6: array, data and key
    • React JS ES6: destructuring
    • React JS ES6: spread operator

    • ReacJS 18: Hooks
    • React JS: Rules of Hooks
    • ReactJS: useState
    • React JS: useReducer
    • React JS: useRef
    • React JS: useEffect
    • React JS: useContext
    • ReactJS: useMemo
    • ReactJS: custom hooks

    • ReactJS: Designing an App
    • React JS App: async
    • React JS App: events
    • React JS App: router
    • React JS App: conditional render
    • React JS App: styling

    • React JS: Laboratories
    • Lab#RE01-1: API Rest Axios
    • Lab#RE02-1: Router & Hooks
    • Lab#RE03-1: to-do app
    • Lab#RE03-2: HighCharts
    • Lab#RE03-3: API Rest Mono
    • Lab#RE03-4: API Rest Domains
    • Lab#RE03-5: data management
    • Lab#RE04-1: todo & server
    • Lab#RE04-2: Spring Boot & ReactJS
    • Lab#RE05-1: chat & websockets
    • Lab#RE05-2: chat: backend
    • Lab#RE05-3: chat & AWS
    • Lab#RE05-4: chat: test ws AWS
    • Lab#RE05-5: chat & front
    • Lab#RE05-6: chat & ws: front
    • Lab#RE06-1: healthyFood Restaurant
    • Lab#RE06-1-PR: create a pull request
    • Lab#RE07-1: traffic lights simulation

    • React JS readings
    • ReactJS Resources
  • Backend
    • Spring Legacy
    • Spring Framework
    • Spring MVC
    • Springs Servlets

    • Spring Boot Basics
    • Spring Boot: fundamentals
    • Spring Boot: create a Project
    • Spring Boot: H2 DB and Thymeleaf
    • Spring Boot: cycle

    • Spring Boot Concepts
    • Spring Boot: Dependency Injection
    • Spring Boot: Annotations
    • Spring Boot: Controller
    • Spring Boot: View
    • Spring Boot: Thymeleaf
    • Spring Boot: Vaadin Flow
    • Spring Boot: Vaadin Hilla
    • Spring Boot: Model
    • Spring Boot: Rest
    • Spring Boot: Data & DB
    • Spring Boot: JPA & DI
    • Spring Boot: JPA Mappings
    • Spring Boot: JPA Relationships
    • Spring Boot: JPA Queries
    • Spring Boot: JPA Inherence
    • Spring Boot: Scaling

    • Spring Boot Laboratories
    • Lab#SB00-1: Library UML
    • Lab#SB00-2: CRUD User
    • Lab#SB00-3: LibraryManagement
    • Lab#SB00-4: API Rest
    • Lab#SB00-5: Rest & JPA-H2
    • Lab#SB00-6: Rest & MongoDB
    • Lab#SB00-7: Styling
    • Lab#SB01-1: DataBase
    • Lab#SB02-1: JPA Relationships
    • Lab#SB03-1: APIs & cloud
    • Lab#SB04-1: JPA Inherence
    • Lab#SB05-1: API Rest
    • Lab#SB06-1: employeeCourse
    • Lab#SB07-1: monitor Book
    • Lab#SB08-1: Restaurant UML
    • Lab#SB08-2: Vaadin
    • Lab#SB08-3: H2 and API Rest
    • Lab#SB08-4: JPA
    • Lab#SB08-5: Test API Rest
    • Lab#SB09-1: SpringIO Conference

    • Spring Boot readings
    • Spring Boot Resources
  • Learning
    • Vocabulary
    • General Vocabulary
    • SCRUM Vocabulary
    • DevOps Vocabulary
    • Java SE Vocabulay
    • Spring Boot Vocabulary
    • DataBase Vocabulary
    • ReactJS Vocabulary
    • Web Vocabulary

    • Learning
    • Useful Questions
    • Learning: tips
    • Writing
    • Taking Notes
    • Comments
    • Document
    • Auto-Evaluate

    • Books & Articles
    • Books
    • Articles

    • What is SCRUM
    • SCRUM Agile Methodology
    • Agile Manifesto & Values
    • SCRUM Guide

    • Scrum Steps
    • Meetings, Impediments and Iterations
    • User stories, Tasks and Habits
    • Delivering Value & Communication
    • ScrumMaster, how it works
    • Mindset, the key to everything
    • Product Owner, how it works
    • Managing Time & Mind
    • Team & the Specialist
    • Albertus’ Dilemma
    • Before SCRUM
    • Team Dynamics
    • Emotions and Thoughts
    • Decision Making and Intuition
    • Beyond SCRUM
    • Balances, atmosphere and tools

    • Resources
    • SCRUM Resources
  • QGIS
    • QGIS basics
    • QGIS: basic concepts

    • QGIS laboratories
    • QGIS Laboratory 1: Introduction to Open Source GIS
  • ArcGIS Pro
    • ArcGIS Pro basics
    • ArcGIS Pro: basic concepts

    • ArcGIS Pro laboratories
    • ArcGIS Pro Laboratory 1: Getting Started
  • Bookmarks
    • Online Resources
    • Online Resources
  • About
    • About me and this site
    • About me
    • About this site
    • About images credit
  • Maps
  • Featured Projects
    • ✈️ Flight tracker
    • 🧑 People tracker
    • 🚗 Renting Car
    • Email
    • GitHub
    • LinkedIn
  1. Python Basics
  2. Python: Functions
  • Python

  • Python Basics
    • Python: Basic Concepts
    • Python: Numbers
    • Python: Strings
    • Python: Conditionals
    • Python: Lists and Loops
    • Python: Nested Loops
    • Python: Tuples
    • Python: Sets
    • Python: Dictionaries
    • Python: Functions
    • Python: Higher-order Functions
    • Python: Variable Scope
    • Python: Variable Assigment
    • Python: None keyword in Python
    • Python: Object Oriented Programming (OOP)
    • Python: Inheritance and Polymorphism
    • Python: Encapsulation
    • Python: Abstraction
    • Python: Exceptions
    • Python: Cheat-Sheets

On this page

  • 1 Overview
  • 2 Functions
  • 3 Function creation
  • 4 Built-in Functions in Python
  • 5 Positional arguments
  • 6 Keyword arguments
  • 7 Optional arguments
  • 8 Parameters vs Arguments
  • 9 Variable scope
    • 9.1 Global Variable
    • 9.2 Local Variable
  • 10 Variables as Parameters
  • 11 Best practices
  • 12 Example of function documentation
  • 13 Recursion
  • 14 Type Hints
  • Edit this page
  • View source
  • Report an issue
  1. Python Basics
  2. Python: Functions

Python: Functions

Python Functions

python
functions
The file system is organized into a hierarchical structure, starting with the root directory
Author

Isaac Boixaderas

Published

Sunday, June 1, 2025

Modified

Sunday, November 16, 2025

1 Overview

📘 Functions in Python

Python functions are blocks of code that perform a specific task and can be called by their name. Functions are defined using the def keyword, followed by the function name and parentheses. The code block within the function is indented and executed when the function is called. Functions can take parameters, which are values that are passed to the function when it is called. Functions can also return values, which are the results of the function’s execution. Functions are a fundamental concept in programming and are used to break down complex problems into smaller, more manageable pieces.

Dictionaries can be created using literals with curly braces, the dict() constructor, or comprehensions. They are versatile for associating data where keys serve as unique identifiers for their values, facilitating fast data retrieval and modification.

2 Functions

Functions in Python are characterized by several key aspects:

  • Definition and Structure: Functions are defined using the def keyword, followed by a unique name and parentheses that may include parameters. The body of the function contains the code to execute, indented according to Python syntax rules.
  • Parameters and Arguments: Functions can accept input through parameters—values provided to the function when it is called. These parameters allow functions to operate on different data inputs dynamically. Python supports various argument types, such as positional, keyword, default, and variable-length arguments.
  • Return Values: Functions can produce output using the return statement, passing a value back to the caller. Not all functions need to return a value; some perform actions without returning data, such as printing to the console.
  • Built-in vs User-defined: Python offers built-in functions like len(), type(), print(), int() and range(), which perform common tasks. Users can also create their own functions, known as user-defined functions, tailored to specific needs.
  • Function Types:
    • Recursive functions call themselves to solve problems through self-reference.
    • Anonymous (lambda) functions are small, unnamed functions created with the lambda keyword, mainly for short operations.
    • Higher-order functions accept other functions as parameters or return functions as results, enabling functional programming paradigms.
  • Function Scope and Lifetime: Functions define a scope—variables created within a function are local to that function unless declared otherwise. This encapsulation helps prevent unintended side effects.

Overall, Python functions are central to writing clean, efficient, and maintainable code by encapsulating reusable logic, managing data flow, and supporting various programming styles, including procedural, functional, and object-oriented paradigms.

3 Function creation

  • Functions are defined using the def keyword.
  • Input variables (parameters/arguments), are specified between parentheses.
# Define a function called `greet`
# It has a `name` parameter

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

  • Function definition:

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


  • This function can now be used anywhere in the code.

  • Call our greet function with the argument “Alice”.

greet("Alice")
Hello, Alice!

  • Optionally, use the return statement to return a value from the function:
def greet(name):
    # Return a string that says "Hello, {name}!"
    return f"Hello, {name}!"

  • Now we can assign the returned value of greet() to a variable.
  • Notice that by default this prints nothing.
alice_greet = greet("Alice")
bob_greet = greet("Bob")
  • We can print the variables:
print(alice_greet)
print(bob_greet)
Hello, Alice!
Hello, Bob!

  • When a value is returned, python exits the function, not executing the rest of the code in the function.
def greet(name):
    print("This code IS executed.")    
    return f"Hello, {name}!"
    print("This code is NOT executed.")
    print("This code is NOT executed.")
alice_greet = greet("Alice")
print(alice_greet)
This code IS executed.
Hello, Alice!

  • We could also use an “empty return” to exit the function.
  • This does not return any value.
def greet(name):
    if name == "Isaac":
        print(f"Hi {name}. You're the professor.")
        return
    print(f"Hi {name}. You're a student.")
greet("Isaac")
Hi Isaac. You’re the professor.
greet("Borja")
Hi Borja. You’re a student.

4 Built-in Functions in Python

  • Built-in functions are regular functions that Python provides by default.
  • Example: how sum() could be implemented in Python:
def sum(lst):
    s = 0
    for value in lst:
        s += value
    return s

5 Positional arguments

  • Positional arguments are passed in the order they are defined.
def greet(name, age):
    print(f"Hello, {name}! You are {age} years old.")

  • "Aclie" and 30 have the same order as name and age in the definition:
greet("Alice", 30)
Hello, Alice! You are 30 years old.

  • If we swap the order of the arguments, name and age have different values inside the function:
greet(30, "Alice")
Hello, 30! You are Alice years old.

  • We get an error if we don’t pass in the correct number of arguments:
greet("Alice")
TypeError: greet() missing 1 required positional argument: ‘age’


greet("Alice", 30, "Bob")
TypeError: greet() takes 2 positional arguments but 3 were given

6 Keyword arguments

  • Are passed by specifying the parameter name and its value.
  • When specifying the names, we can follow any order we like.
greet(age=30, name="Alice") 
Hello, Alice! You are 30 years old.

7 Optional arguments

  • Have default values.
  • Don’t give an error if the optional argument is omitted.
# 'age' is an optional argument with a default value of 25
def greet(name, age=25):
    print(f"Hello, {name}! You are {age} years old.")

  • When calling the greet function without providing a value for age, the function will use the default value instead:
greet("Alice")
Hello, Alice! You are 25 years old.
greet("Alice", 30)
Hello, Alice! You are 30 years old.

  • We can define any number of optional arguments.
  • They must be defined at the tail of the function parameters:
def greet(name, age=25, city="New York"):
    print(f"Hello, {name}! You are {age} years old and you are from {city}.")

greet("Alice")
Hello, Alice! You are 25 years old and you are from New York.

  • We get an error if we define a non-default argument (name) after a default one (age).
def greet(age=25, name, city="New York"):
    print(f"Hello, {name}! You are {age} years old and you are from {city}.")
SyntaxError: parameter without a default follows parameter with a default

8 Parameters vs Arguments

In programming, particularly in Python, the terms “parameters” and “arguments” have distinct meanings:


  • Parameters:

    • Variables defined within the parentheses of a function definition.
    • Act as placeholders for the values that will be passed to the function.
  • Arguments:

    • Actual values passed to a function when it is called.
    • Values are assigned to the corresponding parameters in the function definition.
def greet(name):  # 'name' is a parameter
    print(f"Hello, {name}!")

greet("Alice")  # 'Alice' is an argument
Hello, Alice!

  • However, these terms are often used interchangeably in practice (a lot!).

9 Variable scope

  • Determines the accessibility of a variable.
  • Local variables can only be accessed inside a particular function.
  • Global variables can be accessed throughout the entire program.

9.1 Global Variable

var = "I am a global variable."

def print_global_var():
    # Accessing the global variable within a function
    print(var)

print_global_var()
# Accessing it outside the function
print(var)
I am a global variable.
I am a global variable.

9.2 Local Variable

def print_local_var():
    var2 = "I am a local variable."
    print(var2)

print_local_var()
print(var2)
I am a local variable.
NameError: name ‘var2’ is not defined.

10 Variables as Parameters

  • A function always uses the names defined as parameters.
  • Even if variable names are different outside the function.
  • May be confusing for beginners.

def greet(name, age):
    print(f"Hello, {name}! You are {age} years old.")
user = "Alice"
years_old = 30

# We send variables `user` and `years_old` to `greet`.
# `greet` will use the values of these variables "renamed" as `name` and `age`
greet(user, years_old)
Hello, Alice! You are 30 years old.
# Outside the function we have to keep using the original names
print(user, years_old)
Alice 30

11 Best practices

  • Use descriptive names for functions and parameters.
  • Follow the PEP 8 naming conventions
    • Function names should be in snake case.
  • Each function should perform one specific task.
  • To make your functions easy to understand and use, document them.

12 Example of function documentation

def add(a, b):
    """Add two numbers and return the result.

    Args:
        a (int): The first number.
        b (int): The second number.

    Returns:
        int: The sum of the two numbers.
    """
    return a + b

13 Recursion

  • Recursion is a technique in which a function calls itself.
  • Recursive functions need:
    • Base case, which is the condition that stops the recursion.
    • Recursive case, which is the part that calls the function itself.

  • Example countdown:
def countdown(n):
    # Assume n >= 0
    if n == 0:
        # Base case
        print("GO!!!")
    else:
        # Recursive case
        print(n)
        countdown(n - 1)
countdown(3)
3
2
1
GO!!!

  • Recursion should always have a base case to stop the recursion!
  • Otherwise, the function will call itself indefinitely, leading to an error:
countdown(-1)
-1
-2
-3
…
-2967
-2968
-2969
RecursionError: maximum recursion depth exceeded while calling a Python object

  • Example factorial:
def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)
print(factorial(5))
120

  • Example Fibonacci:
def fibonacci(n):
    if n == 1:
        return [0]
    if n == 2:
        return [0, 1]

    fib = fibonacci(n - 1)
    fib.append(fib[-1] + fib[-2])
    return fib
print(fibonacci(10))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

14 Type Hints

  • Also known as type annotations.
  • Programmer provides hints to the expected types of a function’s input parameters and return value (->).
  • Help make the code:
    • More readable.
    • Self-documenting.
    • Easier to maintain.
    • Can be used by other tools: linters, code editors, static type checkers.

  • Example:
# Identify the type of the `name` (str), `age` (int), and `grades` (int)
# And the return value (str)
def greet(name: str, age: int, grades: list) -> str:
    return f"Hello, {name}! Your average grade is {sum(grades) / len(grades)}."
Back to top
Python: Dictionaries
Python: Higher-order Functions

License: CC0 1.0 Universal

Per aspera, ad astra

  • Edit this page
  • View source
  • Report an issue