Skip to content
Shop

CommunityJoin Our PatreonDonate

Sponsored Ads

Sponsored Ads

Functions & Operators

Functions let you easily reuse code by grouping it together. In this lesson you will learn about functions and operators and how they can be used to run the same code in multiple places.

Cindy
Junior Developer

What is a Function?

A function is a group of related statements. They can take in information (like ingredients for a recipe), do something to it, and then give you something back (like a delicious meal).

For example, you could have a function that adds numbers. You give it two numbers, it adds them up, and then it gives you the answer. Or, you might have a function that checks if a number is even or odd. You give it a number, it checks it, and then tells you if it's even or odd.

python
def add(number1,number2):
    return number1 + number2
print(add(2,3))
python
def even_or_odd(number):
    if number % 2 == 0:
        print('even')
    else:
        print('odd')
even_or_odd(3)

The cool thing about functions is that you can reuse them over and over again. So once you've created a function for adding numbers, you can use it in different parts of your program without having to rewrite the same code again and again! The print() and input() statements are actually functions that are provided for you by Python, but how they work is hidden from us.

Make Your Own Functions

You can create your own functions! To create your own function in Python, follow these steps:

  1. Type def to define a new function.
  2. Give your function a name followed by parentheses and a colon.
  3. Add the statements you want inside the function.
  4. "Call" or use the function.

In hello.py we have a function that stores a greeting in a variable, prints the greeting, gets input from the user on how they are doing and then prints their response back to them. To use the function, call it by typing its name followed by parentheses. You can name your functions whatever you like! Now you can reuse the code over and over without having to type it all out again!

python
def sayHello():
    greeting = "Hello"
    print(greeting)
    response = input("How are you doing today? ... ")
    print("You replied:  " + response)

sayHello()
sayHello()
sayHello()
sayHello()

Note

def means "define a function". This is different in other languages, for example, in Javascript they use the keyword function to define a function.

Passing Arguments to Functions

You can also send data into a function, as well as return data from a function. Just call the function and pass the data into the function:

python
def sayHelloToSomeone(name):
    print("Hello " + name)

sayHelloToSomeone("Tutorial Doctor")
python
def sayHello(name):
    return "Hello " + name

print(sayHello("Tutorial Doctor"))

NOTE

Note: The name inside of the parenthesis is called a parameter and it is a placeholder for the data you will send into the function. When you call the function, you can pass in the data and the data will go where the parameter is. The data you pass into a function is called the argument. Sometimes people get arguments and parameters mixed up.

Also, notice that the sayHelloToSomeone() function looks much like the print() statement. The print() statement is just a function that takes in some data as an argument and prints it to the screen!

You can also pass multiple arguments into a function by separating them with commas.

python
def sayHelloToTwoPeople(me,them):
    print("Hello " + me + " and " + them)

sayHelloToTwoPeople("Tutorial Doctor","Computer")

NOTE

return is another statement that returns something to the user, but it doesn't print it like the print statement does. Sometimes the return statement doesn't return anything, which is what you may want sometimes.

Also, notice that simply returning information from a function will not print it to the screen. You have to use the print() statement to do that. In the example above, we are returning the string "Hello " plus the name argument. When we call the function, it will send us back "Hello Tutorial Doctor". Then we have to print what is returned from the function.

Arguments & Keyword Arguments

If you want to pass an undetermined number of arguments into a function as a list, you can do so using the *args parameter.

If you want to pass an undetermined number of keyword arguments into a function as a dictionary, you can do so using the **kwargs parameter.

python
def numberSet(*args):
    print(args)
    print(args[3])

numberSet(2,3,4,5,6)

Keyword arguments are created using the = sign and use the **kwargs parameter to access them. Inside of the function kwargs is treated like a dictionary

If you want to use both *args and *kwargs, you have to pass in the *args first followed by the **kwargs.

python
def numbersBoth(*args, **kwargs):
    print(args)
    print(kwargs)
    print(kwargs['a'])

numbersBoth("Hello","People",a=2,b=3,c=4)
python
def polynomial(*args,**kwargs):
    # x^2 + 2x + 3y^3 + b
    print(kwargs['x']**2 + 2*kwargs['x'] + 3*kwargs['y']**3 + args[0])

polynomial(7,x=33,y=8)

Naming Conventions

You can name your functions according to what they do (a verb) or what they return (a noun).

In add.py, the add() function adds two numbers together, so we call it add because of what it does. In sum.py, the sum() function returns the sum of two numbers, so we call it sum because of what it returns. In tax.py We called the function totalWithTax because it returns the total price with tax.

python
def add(a,b):
    print(a+b)
python
def sum(a,b):
    return a+b

print(sum(3,4))
add(4,5) #9
python
def totalWithTax(amount,percent):
    return amount * (percent/100) + amount

print(totalWithTax(50,5.00)) #52.5

What are Operators?

An operator is a symbol that represents a function. The + operator is a function that adds two numbers together and returns the answer. In the example below, 1 and 2 are arguments for a function named +

python
print( 1 + 2 )

If this were a function we created, it would look something like this

python
def +(a,b):
    return a + b
print(+(1,2))

NOTE

The code above won't actually work in python and writing +(1,2) looks a little weird, so the people who made python made it easier for us by allowing us to simply write 1 + 2. This is called syntactic sugar (it makes working with the syntax of a language a little sweeter or more pleasant).

If we were to make our own function to add two numbers we could write it this way.

python
def add(a,b):
    return a + b
print(add(1,2))

THINK

What is wrong with this function?

python
def add(a,b):
    return a + b + 1
print(add(1,2))

Math operators

Here are some of the other math operators in Python.

python
# Add Operator
answer = 1 + 3 + 45 + 91
python
# Subtract Operator
expenses = 1,000
income = 2000
net_income = income - expenses
python
# Multiplication
services_requested = 5
price_per_service = 200.00
total_price = service_requested * price_per_service
python
# Division
yearly_cost = 10000
monthly_cost = yearly_cost / 12
daily cost = monthly_cost / 30
hourly_cost = daily_cost / 24
cost_per_minute = hourly_cost / 60
cost_per_second = minute_cost / 60
python
# Exponent
pi = 3.14159265359
r = 4
area_of_circle = pi * (r)**2
python
# Remainder
number = 5
if number % 2 == 0:
    print("the number is even")
else:
    print("the number is odd")
python
# Square Root -> (sqrt)
import math
a = 3
b = 4
c = math.sqrt(a**2 + b**2)
print(c)

Note

Notice that in square_root.py we import math. We will learn about libraries in lesson 6, but Python doesn't have an operator for square roots so we have to use the math library instead.

Let's put it all together by using Python to calculate simple and compound interest. Try to read the code out loud to see if you understand how it works.

python
# Simple Interest
p = 10000
r = .15
t = 5
simpleInterest = p * r * t
print(simpleInterest)      #7500.00
python
# Compound Interest
p = 1000
r = .05
t = 10
n = 365
compoundInterest = p *(1 + (r/n))**(n*t) - p
print(compoundInterest)    #648.6648137652346

We could re-write the code above using functions.

python
def simpleInterest(p,r,t):
    return p * r * t

print(simpleInterest(10000,.15,5))

def compoundInterest(p,r,t,n):
    return p *(1 + (r/n))**(n*t) - p

print(compoundInterest(10000,.05,10,365))

Assignment Operators

An assignment operator is used to assign data to a variable.

Three assignment operators in Python are:

  • Equals(=)
  • Plus Equals(+=)
  • Minus Equals(-=)

The code below assigns age to 38 using the = operator.

python
age = 38

Sometimes you will need to increment a variable by a certain amount. You can do that like this:

python
age = age + 1    #39

A shorthand for the code above uses the += operator

age += 1         #40

The -= operator works similarly

age = age - 1    #39
age -= 1         #38

Note

Other languages also have the ++ and -- assignment operators which add and subtract 1 from the variable it is associated with.

Comparison Operators

A comparison operator compares values/

The comparison operators for Python are:

  • Is Equal(==)
  • Not Equal(!=)
  • Less Than(<)
  • Greater Than(>)
  • Less Than or Equal To(<=)
  • Greater Than or Equal To(>=)
python
myAge = 37
yourAge = 44

print( myAge == yourAge )    #False
print( myAge != yourAge )    #True
print( myAge < yourAge )     #True
print( myAge > yourAge )     #False
print( myAge <= yourAge )    #True
print( myAge >= yourAge )    #False

Logical Operators

Logical operators are used to combine multiple conditional statements into a single statement.

  • AND(and)
  • OR(or)
  • NOT(not)

In other programming languages these operators may look like the following:

  • AND(&&)
  • OR(!!)
  • NOT(!)
python

users = [{
    'username': 'tutorial doctor',
    'password': 'password',
    'role': 'admin'
},
{
    'username': 'guest-user-123',
    'password': 'password',
    'role': 'guest'
},
{
    'username': 'user-456',
    'password': 'password',
    'role': 'admin'
}
]

for user in users:
    if user['username'] == 'tutorial doctor' and user['password'] == 'password' or user['role'] == 'admin':
        print('You have permission!')
    else:
        print("You don't have permission")

Decorator

A decorator is a function that modifies another function. It lets you modify a function without changing the original function. It is useful for running some code before or after a function has run.

This is a decorator function

python
def my_decorator(func):
	return func

To use the decorator, put it on top of another function preceded by an @ symbol. The aFunc() function will become the argument to the my_decorator() function

python
@my_decorator
def aFunc():
	print('hello\n')
aFunc()

Let's run some code before we run the argument function.

python
def decorate_with_bowtie(func):
	print('>-<') 
	return func

@decorate_with_bowtie
def aFunc2():
	print('I am decorated with a bow tie')
aFunc2()

Before aFunc2 runs, we will print('>--<')

Now we are going to wrap the input function and add a bow tie to it

python
def wrap_and_tie(func):
	def wrapped():
		print('>--<')
		func()	
		print('----')
	return wrapped

@wrap_and_tie
def aFunc4():
	print('gift')
aFunc4()

NOTE

Understanding decorators isn't necessary but very useful. We will use decorators in the Backend Development course.

Here is a practical use for a decorator:

python

Syntax: Grammar Rules

Spoken languages have grammar rules and programming languages have syntax. Syntax is the rules about how to structure code so that it works. Here are some syntax rules for Python:

  • Use def to define a function
  • Conditional statements must start with an if and end with an elif or else
python
greeting = "Hello There"
print(greeting)

Semantics

What code means.

The code x+=3 means increment x by three

Your Turn!

Let's build a app!

  1. Open your code editor
  2. Step 2
  3. Step 3

THINK...

Something to think about

Solution
python
Discovery

Something you should have gained from this exercise

Resources

Syntax VS Semantics