In this article, we will learn how to define functions, using the function with variables and function returning value.
In Python, we define a function with a keyword starting with def than the name of the function. A function can have zero or any number of arguments. We will further use the line of codes under the function. To call a function we can call with function name with or without variables.
Syntax:
def funtion_name(var1, Var2, Var3.....varN):
Code line 1...
Code line 2...
Programming function with Zero Argument
Code:
def greater_function():
print("a is greater than b")
def smaller_function():
print("a is smaller than b")
a = 3
b = 7
if a > b:
greater_function()
else:
smaller_function()
Output:
a is smaller than b
Programming function that accepts arguments
We will make a program with basic calculator functionalities that provide addition, multiplication, subtraction and division functions.
Code:
def addition_fun(a, b):
return a + b
def multiply_fun(a, b):
return a * b
def subtraction_fun(a, b):
return a - b
def division_fun(a, b):
return a / b
x = int(input("Enter any integer value: "))
y = int(input("Enter any integer value: "))
print("Result after Addition is {}".format(addition_fun(x, y)))
print("Result after Multiplication is {}".format(multiply_fun(x, y)))
print("Result after Subtraction is {}".format(subtraction_fun(x, y)))
print("Result after Division is {}".format(division_fun(x, y)))
Output:
Enter any integer value: 10 Enter any integer value: 5 Result after Addition is 15 Result after Multiplication is 50 Result after Subtraction is 5 Result after Division is 2.0