Functions
What is a Function?
- A function is a way to organize code into reusable sections.
- It is a group of related statements that perform a specific task.
- You can pass data, known as parameters, into a function.
- A function can return data as a result.
Defining a Function
| def drawSquare():
for i in range(4):
jet.forward(40)
jet.right(90)
|
Passing Variables into a Function
| def drawSquare(distance, angle):
for i in range(4):
jet.forward(distance)
jet.right(angle)
|
Returning a Result From a Function
| def sumNumbers(numbers):
sum = 0
for number in numbers:
sum += number
return sum
|
Calling a Function
| def sumNumbers(numbers):
sum = 0
for number in numbers:
sum += number
return sum
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print('The sum of the numbers from 1 to 10 is: ' + str(sumNumbers(numbers)))
|