In this part of my Learn to Program series I’ll focus on functions. We’ll see what local and global variables are. We’ll solve algebraic equations. We’ll learn how to pass and return an unknown number of values into and out of functions. We’ll generate prime numbers. And, we’ll see how to create small functions that make our code easier to understand.
All of the code follows the video below.
If you like videos like this consider donating a dollar on Patreon.
[googleplusone]
Code & Transcript
# ---------- FUNCTION BASICS ----------
# Functions allow use to reuse code and make the code easier
# to understand
# To create a function type def (define) the function name
# and then in parentheses a comma separated list of values
# to pass if needed
def add_numbers(num_1, num2):
# Return returns a value if needed
return num_1 + num2
# You call the function by name followed by passing comma
# separated values if needed and a value may or may not be
# returned
print("5 + 4 =", add_numbers(5, 4))
# ---------- FUNCTION LOCAL VARIABLES ----------
# Any variable defined inside of a function is available only
# in that function
# ---------- EXAMPLE 1 ----------
# Variables created in a function can't be accessed outside
# of it
def assign_name():
name = "Doug"
assign_name()
# Throws a NameError
# print(name)
# ---------- EXAMPLE 2 ----------
# You can't change a global variable even if it is passed
# into a function
def change_name(name):
# Trying to change the global
name = "Mark"
# A variable defined outside of a function can't be changed
# in the function using the above way
name = "Tom"
# Try to change the value
change_name(name)
# Prints Tom even though the function tries to change it
print(name)
# ---------- EXAMPLE 3 ----------
# If you want to change the value pass it back
def change_name_2():
return "Mark"
name = change_name_2()
print(name)
# ---------- EXAMPLE 4 ----------
# You can also use the global statement to change it
gbl_name = "Sally"
def change_name_3():
global gbl_name
gbl_name = "Sammy"
change_name_3()
print(gbl_name)
# ---------- RETURNING NONE ----------
# If you don't return a value a function will return None
def get_sum(num1, num2):
sum = num1 + num2
print(get_sum(5, 4))
# ---------- PROBLEM : SOLVE FOR X ----------
# Make a function that receives an algebraic equation like
# x + 4 = 9 and solve for x
# x will always be the 1st value received and you only
# will deal with addition
# Receive the string and split the string into variables
def solve_eq(equation):
x, add, num1, equal, num2 = equation.split()
# Convert the strings into ints
num1, num2 = int(num1), int(num2)
# Convert the result into a string and join (concatenate)
# it to the string "x = "
return "x = " + str(num2 - num1)
print(solve_eq("x + 4 = 9"))
# ---------- RETURN MULTIPLE VALUES ----------
# You can return multiple values with the return statement
def mult_divide(num1, num2):
return (num1 * num2), (num1 / num2)
mult, divide = mult_divide(5, 4)
print("5 * 4 =", mult)
print("5 / 4 =", divide)
# ---------- RETURN A LIST OF PRIMES ----------
# A prime can only be divided by 1 and itself
# 5 is prime because 1 and 5 are its only positive factors
# 6 is a composite because it is divisible by 1, 2, 3 and 6
# We'll receive a request for primes up to the input value
# We'll then use a for loop and check if modulus == 0 for
# every value up to the number to check
# If modulus == 0 that means the number isn't prime
def isprime(num):
# This for loop cycles through primes from 2 to
# the value to check
for i in range(2, num):
# If any division has no remainder we know it
# isn't a prime number
if (num % i) == 0:
return False
return True
def getPrimes(max_number):
# Create a list to hold primes
list_of_primes = []
# This for loop cycles through primes from 2 to
# the maximum value requested
for num1 in range(2, max_number):
if isprime(num1):
list_of_primes.append(num1)
return list_of_primes
max_num_to_check = int(input("Search for Primes up to : "))
list_of_primes = getPrimes(max_num_to_check)
for prime in list_of_primes:
print(prime)
# ---------- UNKNOWN NUMBER OF ARGUMENTS ----------
# We can receive an unknown number of arguments using
# the splat (*) operator
def sumAll(*args):
sum = 0
for i in args:
sum += i
return sum
print("Sum :", sumAll(1,2,3,4))
# ---------- pythontut2.py ----------
# We need this module for our program
import math
# Functions allow us to avoid duplicate code in our programs
# Aside from having to type code twice duplicate code is bad
# because it requires us to change multiple blocks of code
# if we need to make a change
# ---------- OUR FUNCTIONS ----------
# This routes to the correct area function
# The name of the value passed doesn't have to match
def get_area(shape):
# Switch to lowercase for easy comparison
shape = shape.lower()
if shape == "rectangle":
rectangle_area()
elif shape == "circle":
circle_area()
else:
print("Please enter rectangle or circle")
# Create function that calculates the rectangle area
def rectangle_area():
length = float(input("Enter the length : "))
width = float(input("Enter the width : "))
area = length * width
print("The area of the rectangle is", area)
# Create function that calculates the circle area
def circle_area():
radius = float(input("Enter the radius : "))
area = math.pi * (math.pow(radius, 2))
# Format the output to 2 decimal places
print("The area of the circle is {:.2f}".format(area))
# ---------- END OF OUR FUNCTIONS ----------
# We often place our main programming logic in a function called main
# We create it this way
def main():
# Our program will calculate the area for rectangles or circles
# Without functions we'd have to create a giant list of ifs, elifs
# Ask the user what shape they have
shape_type = input("Get area for what shape : ")
# Call a function that will route to the correct function
get_area(shape_type)
# Because of functions it is very easy to see what is happening
# For more detail just refer to the very short specific functions
# All of the function definitions are ignored and this calls for main()
# to execute when the program starts
main()
# ---------- HOMEWORK ----------
# Add the ability to calculate the area for parallelograms,
# rhombus, triangles, and trapezoids