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
choice = input("Enter choice(1 or 2): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
elif choice == '2':
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)
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.
def draw_square(t, sz):
"""Make turtle t draw a square of sz."""
for i in range(4):
wn = turtle.Screen()
wn.title("Turtle using functions")
a = turtle.Turtle()