Do you know what Subprograms are in Python?
Contents
Introduction
A subprogram is a block of code that only runs when called in your program. The purpose of a subprogram is to perform a specific task. Subprograms are very useful if you want to avoid writing code that does the same thing over and over.
Like in Python OOP, you might want to have a main subprogram that joins the other subprograms together and run the program, and other subprograms that do their own specific tasks.
Writing the Code
This time, we’ll create a program that helps you with addition problems!! But we’ll only be using subprograms.
Defining Subprograms
To use a subprogram we need to define it first. We’ll start with our main subprogram-
def main():
The def keyword is short for define. Python must have read this line first so it knows about it. Python reads from top to bottom so you should define your subprogram at the lines above the code you use to call it.
Now we start asking the user for the numbers in their math problem.
def main():
print("Addition Helper")
num_1 = int(input("Enter first number: ")
num_2 = int(input("Enter second number: ")
Calling your Subprograms
In coding, ‘calling’ lets your computer know that it should run the code. To call a subprogram, you just have to type the name and parentheses (brackets), like this-
def main():
print("Addition Helper")
num_1 = int(input("Enter first number: ")
num_2 = int(input("Enter second number: ")
main()
We’ll add code in main later on. Now we start working on the addition subprogram!
Arguments
def addition(num_1,num_2):
ans = num_1 + num_2
print(ans)
In the addition subprogram, it will add up the two numbers the user gave. In subprograms, one subprogram cannot access a value in another subprogram.
You cannot use code that is created and written in another program! You will have to import it to your program so that it can be used.
The same thing applies to subprograms. They are called sub-programs, they are like smaller programs written in a larger program. So despite being in the same program, you still have to get permission to access the values.
Arguments are information that are passed into subprograms. In line 1, num_1 and num_2 are examples of arguments. You pass them around in the parentheses of the subprogram, separated by a comma.
You can also use the return keyword to let other subprograms use the value!
Results
Now, we call the addition subprogram in main, and we’re ready to go!
def addition(num_1,num_2):
ans = num_1 + num_2
print(ans)
def main():
print("Addition Helper")
num_1 = int(input("Enter the first number: "))
num_2 = int(input("Enter the second number: "))
addition(num_1,num_2)
main()
The result-
Addition Helper
Enter the first number: 1
Enter the second number: 1
2
Conclusion
That’s all for my Subprograms guide! I hope you found it helpful.
