Skip to main content
Practice

Functions: Defining and Calling

Functions let us group reusable code under a name. This makes code more organized and avoids repetition.

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


1. Defining a Function

Use def to define a function. Include 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 take input values (parameters) to perform different actions based on the input.

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 send back a result 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 callRuns the code inside the function
ParametersInputs to customize behavior
returnSends back a value

Want to learn more?

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