In the previous blogs/chapter, we learned that small code increases a program clarity to read and modify. As we continue learning Python, we will see large codes. Now assume, we may need to write the same code again and again, it becomes very tedious task for programmer/coder.
To handle this issue, we use function which makes program clearer, well-structured and more understandable. Also, it is used anytime and anywhere within the program.
What is Function in Python programming?
Function is a block of code that we can use it in our existed code when needed.
Syntax:
def function_name():
code
Here: def: Use to define a function, function_name: name of the function, (): parentheses (can hold parameters), : start of function block
Example:
def welcom_msg():
print("Hello Guys, Welcome to Quillix Blogspot")
welcom_msg()
Perameter and Arguments
In a function definition, parameters are variables inside parentheses and arguments are values that are passed when the function is called.
Example:
def pmter_argu(Name): # Name - is Parameter
print("Hello," Name)
pmter_argu("Somit") # Somit - is argument
Return Statement
def sum_two(a, b):
return (a+b)x = sum_two(10, 20)
print(x) #Output: 30
Default Parameter
You can also give a default parameter value that executes when user does not provide any value.
Example:
def df_ptm_val(name = "Guest"): #default value
print ("Hello", name)df_ptm_val() #Output: Hello, GuestMultiple Value Return
def multi_val(a, b):
return a+b , a-b #multiple value returnx = multi_val(10,5)
print(x) #Output: 15, 5Local and Global Variable
x = 10 #Global Variabledef num():
y = 5 #Local variable
print(y)
print(x)
num() #Output: 5 10Create Simple Calculator
print("Simple Calculator")
def calculator():
a = int(input("Number 1: "))
b = int(input("Number 2: "))
operator = input("Operator(+ or -): ")
if operator == "+":
print (a+b)
elif operator == "-":
print (a-b)
else:
print ("Only Addtion and Substraction")
calculator()
