How to use arguments in Python funtions

How to use arguments in Python funtions

What is an argument?

In programming, an argument is an input that you give to a program to work with. Giving arguments to our functions makes them dynamic, it will allow other people to be able to use our functions by passing their own arguments to our functions.

Arguments are like variables. They are containers that hold values only in that function.

Example: If I want to add two numbers, I can do it this way.

def add_two_numbers():
    first_number = 5
    second_number = 4
    sum = first_number + second_number
    print("The sum of the two numbers is ", sum)

Whenever we call this funtion, it will print the addition of 4 and 5 which is 9. This might not always be good.

# it will print out 9
add_two_numbers()

What if someone wants to add the numbers 3 and 7 or any other two numbers, they will not be able. It means that this program we have written is not useful to other people. We have to allow people to be able to pass their input into our programs and use it they way they want to use it. To do this, we have to use arguments which are empty variables that will contain values at run time.

How to assign arguments to a function.

We can assign arguments to functions by placing them in between the parenthesis of the function. Example: We are going to place first_number and second_number inside a the parenthesis. This way, they become arguments to the function.

def add_any_two_numbers(first_number, second_number):
    sum = first_number + second_number
    print("The sum of the two numbers is ", sum)

How to call a function with arguments.

Please, pay close attention here. Calling a function with arguments is like calling any other function, but here, we have to put values that are to be held where the name of the argument was. Look carefully:

add_any_two_numbers(3, 7)

The first number is placed before the comma. The argument before the comma is first_number. So first_number will be the container holding the value 3. The arguement after the comma is second_number, it will be the container holding the value 7. We could put other values in there if we wanted.

For example

add_any_two_numbers(5, 8)
add_any_two_numbers(10, 6)
add_any_two_numbers(4, 9)
add_any_two_numbers(2, 17)
add_any_two_numbers(25, 17)

As you can see other people can now use our functions to add whatever two numbers that they want to add.

Conclusion

The is basically one more thing we need to know about function to be through. Although there are other things. It is called Return. In future post, I hope to explain it. The other things are: Global and local scope, key word arguments and some other few concepts. I would highly recommend that you write some programs using what you have learnt. God bless you.