Skip to main content
Practice

Functions: Defining and Calling

Functions let you group reusable code under a single name. This makes your programs cleaner, easier to read, and free of repetition.

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


1. Defining a Function

Use def to define a function. Add parentheses (with or without parameters) and end the line with a colon (:).

Defining a Function
def greet():
print("Hello, welcome!")
  • The function is named greet.
  • It has no parameters.
  • When called, it prints a greeting.

2. Calling a Function

Once defined, you can call the function by writing its name followed by parentheses.

Calling a Function
greet()
  • This line runs the greet() function and prints the message.

3. Function with Parameters

Functions can accept input values, known as parameters, to perform actions that depend on those inputs.

Function with Parameters
def greet_user(name):
print("Hello,", name)

greet_user("Alice")
  • greet_user takes one argument called name.
  • When called with "Alice", it prints: Hello, Alice.

4. Returning Values

Functions can produce and send back results using the return statement.

Returning Values
def add(a, b):
return a + b

result = add(5, 3)
print(result)
  • add takes two arguments and returns their sum.
  • The result is stored in result and printed.

Summary

ConceptDescription
defKeyword to define a function
Function callExecutes the code inside the function
ParametersInputs to customize behavior
returnSends back a value to the caller

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.