Python Functions
Python functions are blocks of code that are only run when called. Data known as parameters can be passed into a function and data can be returned as the result of a function. When using decomposition to break a problem down into smaller, easier parts functions can be used to handle seperate parts of the problem.
Task: The program has two functions. The first function is used to add numbers, the second is used to subtract. Depending on what option the user picks a different function is called.
- Run the code to check it works.
- Improve the model by creating two new functions to allow numbers to be divided and multiplied.
- Add # comments to explain what your code does.
- Add screenshots of the code to your notes in powerpoint.
- Can you develop the model further to calculate squared numbers, cubed numbers and square roots?
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
print("Select operation.")
print("1.Add function")
print("2.Subtract function")
choice = input("Enter choice(1 or 2): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
else:
print("Invalid input")
Default values can be added to functions that will return a default value. See below.....
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Create a function similar to the one above with a default value of 'Parker' that states what school you go to.
The code below uses a function to draw a square using turtle. See if you can develop this code so that the user can select different shapes to draw. Depending on the option chosen python should run a different function.
import turtle
def draw_square(t, sz):
"""Make turtle t draw a square of sz."""
for i in range(4):
t.forward(sz)
t.left(90)
wn = turtle.Screen()
wn.bgcolor("lightgreen")
wn.title("Turtle using functions")
a = turtle.Turtle()
draw_square(a, 50)
wn.mainloop()