WEB DEVELOPER SITE
PHP7
 

Python Functions


Python gives you many built-in functions like print()


Function syntax

Function start with keyword def by function name and (( ))

here a example of syntax


def printso( str ):
   

"This prints a passed string into this function"

print str return

Calling a function

It can execute it by calling it from another function or directly from the Python prompt

def my_function():
  print("Hello world!")

my_function()
Result Answer: Hello World!
Run Example »

Scope Variable

you can access a particular identifier
  • Global variables
  • Local variables

Global variable Vs Local variable

global variable declared outside a function and inside a function where as local variable declared only inside the function. Example of Global variable
testVar = 0

def testFunc():
    global testVar
    testVar += 1

print testVar
testFunc()
print testVar

Output:
>>>
0
1

Return statement

To let a function return a value, use the return statement: # Now you can call sum function
total = sum( 20, 30 );
print "Outside the function : ", total 

outside the function 50
second example

def my_function(x):
  return 2 * x

print(my_function(12))
print(my_function(35))
print(my_function(49))

Run Example »

Default arguments

The following example shows how to use a default parameter value.
If we call the function without parameter, it uses the default value:

Example of Default arguments


#!/usr/bin/python

# Function definition is here
def printinfo( name, age = 35 ):
   "This prints a passed info into this function"
   print "Name: ", name
   print "Age ", age
   return;

# Now you can call printinfo function
printinfo( age=35, name="Minaj" )
printinfo( name="Minaj" )
$python2.7 main.py Name: Minaj Age 35 Name: Minaj Age 35 Run Example »