In this video I’ll explain how to use functions in Python 2.5 through 2.7. I’m going to cover how to:
- Create Functions
- Pass Values to Functions
- Create Default Values
- Except Unlimited Arguments
- Except Unlimited Key Value Pairs
- Use Recursion
- and more…
Like always, the code follows the video. If you have any questions or comments leave them below. And, if you missed my other Python Tutorials they are available here:
- Python 2.7 Tutorial Pt 1 : Importing Modules and variable types
- Python 2.7 Tutorial Pt 2: Python Lists & Tuples
- Python 2.7 Tutorial Pt 3: The Print Function & Dictionaries
- Python 2.7 Tutorial Pt 4: The IF Statement & Conditional Expression
- Python 2.7 Tutorial Pt 5: Looping with While and For
Here is Some Code that Demonstrates using Python Functions
#! /usr/bin/python
# Define a docstring a special function attribute
globalVariable = 10
def addNumbers(NumOne=1,NumTwo=1):
‘Adds the numbers passed to it’
return NumOne + NumTwo
def addUndefNums(NumOne=1,NumTwo=1,*args):
‘Adds the numbers passed to it’
finalValue = NumOne + NumTwo
if args:
for i in args:
finalValue += i
return finalValue
else:
return finalValue
def scopeFunction():
mainNumber = 10
print id(mainNumber)
print “mainNumber equals”, mainNumber, “in function scopeFunction”
return
def changeGlobal():
globals()[‘globalVariable’] = 20
return
def createDict(**kvargs):
for i in kvargs:
print i, kvargs[i]
print type(kvargs[i])
print type(kvargs)
print kvargs
return
def factorial(num):
if num == 1:
return 1
else:
return num * factorial(num – 1)
def printNames(first,last):
pass
def main():
# Demonstrate difference between global & local scope
mainNumber = 5
print “mainNumber equals”, mainNumber, “in function main”
scopeFunction()
print “mainNumber equals”, mainNumber, “after scopeFunction”
print id(mainNumber)
# Force a global variable to change
print “globalVariable before changeGlobal =”, globalVariable
changeGlobal()
print “globalVariable after changeGlobal =”, globalVariable
# Create a function with a docstring
print addNumbers(1)
print addNumbers.__doc__
# Add undefined number of numbers with a tuple
print addUndefNums(1,2,3,4,5,6,7,8)
# Create a dictionary
createDict(Name=’Derek’, Age=35, YearBorn=1974)
createDict(Cust1=(‘Derek’,35,1974),Cust2=(‘Sally’,25,1984),Cust3=(‘Paul’,15,1994))
# Demonstrate Recursion
print factorial(3)
“””
Demonstrate Recursion
def factorial(3):
if 3 == 1:
return 1
else:
return 3 * factorial(2)
def factorial(2):
if 2 == 1:
return 1
else:
return 2 * factorial(1)
def factorial(1):
if 1 == 1:
return 1
“””
if __name__ == ‘__main__’: main()











