python function examples

Python function is declared by the keyword def.

#!/usr/bin/env python

#A function returns the sum of two numbers.
def add(a, b):
    return a + b

#A function returns the difference of two numbers.
def substract(a, b):
    return a - b

#A function returns the multiplication of two numbers.
def multiply(a, b):
    return a * b

#A function returns the division of two numbers.
def divide(a, b):
    return a / b

#Getting inpputs, and convert the string to integer
a = int(raw_input("Enter a number: "))
b = int(raw_input("Ender a number greater than 0: "))

#Calls each of the function and prints the result
print a,"+",b,"=",add(a,b)
print a,"-",b,"=",substract(a,b)
print a,"*",b,"=",multiply(a,b)
print a,"/",b,"=",divide(a,b)

Output:

Enter a number: 4
Ender a number greater than 0: 2
4 + 2 = 6
4 - 2 = 2
4 * 2 = 8
4 / 2 = 2

Search within Codexpedia

Custom Search

Search the entire web

Custom Search