Reuse code with functions

Most programming languages let you create reusable, shareable code with functions. A function is a chunk of code that you separate out from the rest of your program, give a name, and then call from your code.

Different languages have different ways of creating functions. In Python, use the def keyword to define a new function. Here's some Python code that defines a make smoothie () function:

The parentheses are important, V^ ^ so be sure to include them-

juice = input("What juice would you like? ") fruit = input("OK - and how about the fruit? ") print("Thanks. Let's go!") print("Crushing the ice...") print("Blending the " + fruit)

print("Now adding in the " + juice + " juice") print("Finished! There's your " + fruit + " and ft iunttion is a boxed-«? reusable code-

In Python, it's important that you define the function before you use it, so make sure the code that calls (or uses) the function comes after the definition of the function:

Call the function. Note the" use of parens.

print("Welcome to smoothie-matic 2.0") another = "Y" while another == "Y": make_smoothie()

another = input("How about another(Y/N)? ")

Every time that Python sees make smoothie() in the code, it jumps to the code in the make smoothie() function. It runs the code in the function until it gets to the end, and then returns to the next line in the code that called it.

Let's use functions to share code within your program.

Code Magnets

Before you amend the existing coffee bean program code, let's see if you can create a function to display the current bean price. Rearrange the magnets in the correct order to create the function:

page = urllib.request.urlopen("http://www.beans-r-us.biz/prices.html")

get_price() |

get_price() |

Code Magnets Solution

Before you amend the existing coffee bean program code, let's see if you can create a function to display the current bean price. You were to rearrange the magnets in the correct order to create the function:

Yo« stiii need ^ >»K1,wf,ts before usmg them in a WW-

import urllib.request

The function def inition | def 11_

You need a Colon aftev-"the function name.

get_price()

get_price()

The body of the funcW needs to be indented.

The function needs to be declared before it's called-

page = urllib.request.urlopen("http://www.beans-r-us.biz/prices.html")

print( II text[start_of_price:end_of_price]

The f unction def inition ends here-

This line isn't indented, because it is pavt of the main pvogvaw,.

Was this article helpful?

0 0

Post a comment