Learn > Higher Computing Science > 7. Functions > 7.1 – Square function

7.1 - Square function

Problem

Create a function that will square a number.

It must match the top level design and data flow.

Example run

Enter number to square: 9
Answer = 81
1 Square a number IN num
OUT result
  1. result = num * num
  2. return num

 

 

# Main 
number = int(input("Enter number to square:"))
answer = square(number)
print("Answer =", answer)
def square(num):
    result = num * num
    return result

# Main 
number = int(input("Enter number to square:")) 
answer = square(number) 
print("Answer =", answer)
def square(num):
    result = num * num
    return result # Send the value in result to where the function was called

# Main 
number = int(input("Enter number to square:")) 
answer = square(number) # Set answer to the value returned by the square() function
print("Answer =", answer)

Extension

Change the square function intoa power function. It should take two parameters and return the result.

power(2,4) -> 16