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!

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

# Now you can call sum function
total = sum( 20, 30 );
print "Outside the function : ", total 

outside the function 50

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