In this tutorial you will learn:
Functions in Python
Functions, one of the most fundamental concepts in programming. Functions help us in modularizing our code it means that we put the most commonly used code in a function block and now we don’t need to write that code again. We can simply call the function again wherever it is required. We can even call a function in a for loop, one good example would be to call a function that gives us a sum for a series of numbers. Some functions that we have been using are called built in functions, these are provided by the programming language e.g the most commonly used print function. Here is how we can define a function.
- print("Output Result")
- def myFunction():
- print("I love Python")
When we create a function we need to call it anywhere in our code and that can be done with a simple syntax defined in the example.
myFunction() #It’s as simple as that
So every time we call this function Python it will print(“I love Python”). If we call it in a for loop 3 times it will print this function 3 times.
- print("\nPrinting I love Python 3 times")
- for i in range(3):
Passing parameters to functions
We can pass values to a function from our code as well. Suppose we need a function to combine two words so we can use the code used in the example below
- print("\nCombining two words")
- def combine(a,b):
- print(a," ",b)
- combine("Hello", "Python")
Returning values from a Function
Functions can also return values for example result of a computation. Suppose we need to find sum of two numbers or square of two functions then we can pass the numbers and return the output result from the function.
- print("\nSumming and Squaring numbers")
- def sum(a, b):
- return a + b
- print("Sum of 10 and 20 is : ", sum(10, 20))
- def square(a):
- return a*a
- for i in range(10):