Functions Tutorial

Functions are blocks of code designed to accomplish a single task.

They can be combined with other functions to make programs that are cleaner and more efficient.

In Python, the general form of a function is as follows:

def functionName(functionParameters):

Function parameters are data that the function takes in and uses in the function.

For example, a function to add two numbers will take in two integers as its parameters and return the sum.

Functions will normally result in printing some text or returning some value.

They can be reused over and over by calling the function in your main program like this:

Today, we will create and run some simple functions, and then we will implement functions into the rock, paper, scissors game we previously made. If you haven’t seen that previous tutorial, insert shameless plug here. (Hyperlink that if possible chief)

Basic Functions:

1. A function to return the sum of two given numbers: a, b.
def returnSum(a, b):   return a + b

Some ways to call this function:

print(returnSum(3, 5))

or

firstNum = 14, secondNum = 99print(returnSum(firstNum, secondNum))

2. A function to check if a number is even.

def isEven(a):   if a % 2 == 0:
print (a, “is even.”)
else:
print (a, “is odd.”)

Some ways to call this function:

isEven(214)

or

x = 9
isEven(x)

3. A function that generates two random numbers, gets the sum, and checks if the sum is equal to 21.

import random
def getTwentyOne():
print(“Let’s Get 21!\n”)
first = random.randint(1, 11)
second = random.randint(1, 11)
sum = first + second
print(“First Number:”, first)
print(“Second Number:”, second)
print(“Sum:”, sum)
if sum == 21:
print(“You hit 21 exactly!\n”)
elif sum < 21:
print(“You got below 21 :)\n”)
else:
print(“You busted over 21 :(\n”)

How to call this function:

getTwentyOne()

Implementing Functions Into Rock Paper Scissors:

* Make sure you checked out our previous tutorials on lists and dictionaries !

1. We will be changing two things into functions: the user making a valid move and the computer asking the user if they want to play again.
2. For the player picking an option, we want our function to return their choice, so we can store it in a variable. Note the addition of the line “return choice”:
def goodChoice():
validSelection = False

while not validSelection:
choice = input(“rock, paper or scissors?: “).lower().strip()
if(choice in options):
validSelection = True
return choice
else:
print(“Please try again. Enter a valid option.\n”)

In the main game loop, we can then assign the player’s move like this:

userSelection = goodChoice()

3. For when the computer asks the player to play again, we want the return value to be the boolean value keepPlaying that controls the main game loop. Note the two return statements in the if statement block:

def playAgain():
checkReplay = “”
checkReplay = input(“Wanna play again?: “)
validSelection = False
print(“\nThanks for Playing!”)
return False
else:
return True

In the main game loop, we would call the function like so:

keepPlaying = playAgain()

4. Now, our main game loop looks like this:

print(“Let’s Play Rock, Paper, Scissors!\n”)while keepPlaying:
userSelection = goodChoice()
computerSelection = random.choice(options)

print(“You Chose: “ + userSelection + “ The Computer Chose: “ + computerSelection)
for outcome in results:
if (userSelection, computerSelection) in results[outcome]: