Table of Contents

Introduction to using functions in Python

Example Description
See an example of a function call and discover how a common error can be fixed by placing the function definition before the function call.

Introduction:

In this Python code example, we are exploring the concept of functions. Functions are blocks of code that can be defined and called multiple times, allowing for code organization and reusability. In this example, we have a function called `helloPython()` that simply prints the message “I love Programming”. However, we encounter a common error when trying to call the function. Let’s analyze the code and fix the error.

Code:

#print using functions
helloPython() #Function Call
def helloPython(): #Function definition
 print("I love Programming")

Logic:

  1. We start by defining the function `helloPython()`, which does not take any arguments.
  2. Inside the function, we use the `print()` function to display the message “I love Programming”.
  3. We then try to call the function `helloPython()` after its definition.
  4. However, we encounter a `NameError` because the function call is made before the function definition.
  5. To fix the error, we need to move the function definition `helloPython()` above the function call.

Output:

>> I love Programming