CISC 101 - Day 3

2024-09-19 15:03:03 -0400 EDT


Functions

Definition: a function is a named sequence of statements that performs a computation when called upon. We use functions to reuse them through out our code instead of writing the same block of code every time you need it, you just call it. You call it by writing its name and passing an argument if required. arguments are passed with a parenthesis directly to the right of the function.

Think of the print function $\rightarrow$ You call the function by writing its name, print, then writing what you want to print, the argument, next to it in parentheses. print is one of many built-in functions. The most common are functions that convert a variable form one data type to the next.

Using Modules

Python also has a wide array of math based functions that you can access with the math module. you can add this to your program by import math at the beginning of your program. you can find log functions, trig functions, the exact value of pi and more. Just now that when referring to a function imported from a module, use ’name_of_module.func_name’. For example:

import math

a = math.pi

print(math.sin(a))

Another important module is the random module. you can generate random numbers via a multitude of different algorithms, pick random entities from a list, shuffle a list, generate a range, etc

You can read about more in the python documentation.

Making Functions

we can create a new function by declaring it with a “def” indicator.

def add():
    a + b = c

a = 2
b = 3
c = 0

add()

print(c)

This creates a the function add, which make c equal to the sum of a and b. we call our function with the syntax as any other function. you call other functions inside your function - python will keep track where the flow of execution is.

if you want to add arguments to your functions, you add parameter(s) when you declare it.

def add(x, y):
    x + y = c

a = 2
b = 3
c = 0

add(a, b)

print(c)

add(b, c)

print(c)

You can make this more interesting by making the parameters of the function input variables

def add(x, y):
    result = x + y
    print(result)

a = int(input('give me a number: '))
b = int(input('give me another number: '))

add(a, b)