Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python functions

'''
Functions are very useful in python because you can use them instead
of repeating code in your program which makes your code messy.
'''

# This is how you create a function
def functionName():
  print('Hello World!')
  
functionName() # prints out 'Hello World!'
functionName() # prints out 'Hello World!' again

# Functions can have attributes which you insert into the function
def add(a, b):
  print(a + b)
  
add(2, 4) # prints out '6'
add(11, 35) # prints out '46'

# Finally, functions can return values which you can save as variables
def addFive(value):
  return value + 5

myVar = addFive(3) # myVar becomes equal to 8 (3 + 5)
print(myVar) # prints out myVar

'''
Keep in mind that scope comes into play in your functions. If you
create a variable in a function, it won't be saved outside the
function.
'''
def createVar():
	myVar = 5
    
createVar()
print(myVar) # returns error (unless you defined myVar outside function)
Source by www.codegrepper.com #
 
PREVIOUS NEXT
Tagged: #python #functions
ADD COMMENT
Topic
Name
7+2 =