Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære How to Create Functions in Pythons | Functions in Python
Introduction to Python (dev copy)

bookHow to Create Functions in Pythons

In earlier examples, like those in the "Conditional Statements" section, we often assigned different values to a variable just to verify our code was functioning correctly. This method can be cumbersome, especially as our code grows more extensive. A more efficient approach involves using functions. Here's the general syntax for defining a function:

def function_name(var1, var2...):
  function_body
  return something

Note

All lines of code within the function's body must have consistent indentation, whether it's 2 spaces, 3, 4, or another value.

For instance, let's craft a basic function that takes in two numbers (we'll call them a and b) and returns the square of their sum.

123456
# Define function def sum_squared(a, b): return (a + b)**2 # Call function print(sum_squared(2, 3))
copy

Success! Indeed, 2 + 3 equals 5, and 5 squared is 25.

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 6. Kapittel 3

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Awesome!

Completion rate improved to 1.64

bookHow to Create Functions in Pythons

Sveip for å vise menyen

In earlier examples, like those in the "Conditional Statements" section, we often assigned different values to a variable just to verify our code was functioning correctly. This method can be cumbersome, especially as our code grows more extensive. A more efficient approach involves using functions. Here's the general syntax for defining a function:

def function_name(var1, var2...):
  function_body
  return something

Note

All lines of code within the function's body must have consistent indentation, whether it's 2 spaces, 3, 4, or another value.

For instance, let's craft a basic function that takes in two numbers (we'll call them a and b) and returns the square of their sum.

123456
# Define function def sum_squared(a, b): return (a + b)**2 # Call function print(sum_squared(2, 3))
copy

Success! Indeed, 2 + 3 equals 5, and 5 squared is 25.

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 6. Kapittel 3
some-alt