⬅ Previous Topic
Infinite Loops and Exit ConditionsNext Topic ⮕
Function Parameters and Return Values⬅ Previous Topic
Infinite Loops and Exit ConditionsNext Topic ⮕
Function Parameters and Return ValuesIn programming, a function is a named block of code that performs a specific task. It can be defined once and called (or reused) multiple times, making code modular, clean, and easier to maintain.
At a basic level, a function includes:
function greetUser(name):
print "Hello, " + name + "!"
Here, greetUser
is the function name. It takes one parameter name
and prints a greeting message.
Once defined, a function can be called using its name followed by parentheses containing arguments:
greetUser("Alice")
Hello, Alice!
function showWelcomeMessage():
print "Welcome to the Programming Course!"
showWelcomeMessage()
Welcome to the Programming Course!
This function doesn’t take any input but simply prints a message when called.
function add(a, b):
result = a + b
return result
sum = add(5, 3)
print sum
8
The add
function takes two inputs and returns their sum, which can be stored or printed.
Question: Can a function return nothing?
Answer: Yes. Some functions perform actions (like printing to screen or saving a file) and do not need to return a value.
function logActivity(activity):
print "Logging activity: " + activity
logActivity("User logged in")
Logging activity: User logged in
Once you define a function, you can use it as many times as needed:
logActivity("File uploaded")
logActivity("Email sent")
Logging activity: File uploaded Logging activity: Email sent
Question: What if you want to repeat a calculation many times?
Answer: Wrap it in a function! That way, you don’t repeat logic — just call the function with different inputs.
Functions are fundamental building blocks in programming. They help you:
Mastering functions is essential to writing clean, scalable programs!
⬅ Previous Topic
Infinite Loops and Exit ConditionsNext Topic ⮕
Function Parameters and Return ValuesYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.