5. Functions - JulTob/Python GitHub Wiki

Statements that perform a task.

def fname(<parameters>):
    ‘’’doc string’’’
    <statements>
    return <expression>

‘’’Call to function’’’
fname(<parameters values>)

fname.__doc__ 
>>> doc string

def triangle_area(base, height):
    ‘’’Returns the Area’’’
    area = 0.5 * base * height 
    return area

triangle_area(base=3, height=4)
triangle_area(3, 4)




def set_global_var:
    global global_var 
    f = 101

A function does not change the external values of the variables. The internal variables only exist in execution.

def sum (a,b):
    printa is”,a 
          a= a+b
    printa is”,a 
    return a
a=2
b= 123
print (sum (a,b) )


print(a)
# a doesn’t change 








>> a is 2
a is 125
125

>> 2




def sounds( vocal = 'a', length = 1):
    print (vocal*length)
# Why Python Is Great:
# Function argument unpacking

def myfunc(x, y, z):
    print(x, y, z)

tuple_vec = (1, 0, 1)
dict_vec = {'x': 1, 'y': 0, 'z': 1}

>>> myfunc(*tuple_vec)
1, 0, 1

>>> myfunc(**dict_vec)
1, 0, 1

Using function from in-built modules e.g. Import function sqrt from the math module. To get a list of supported modules, use help("modules").

from math import sqrt

# Get value from the user
num = eval(input("Enter number: "))
# Compute the square root
root = sqrt(num);

# Report result
print("Square root of", num, "=", root)
User-defined functions
# Count to ten and print each number on its own line
def count_to_num(n):
    for i in range(1, n+1):
        print(i)

print("Going to count to ten . . .")
count_to_num(10)
⚠️ **GitHub.com Fallback** ⚠️