# Writing Functions in Python

Within the Python interactive development environment (IDLE), writing functions is the beginning of true programming. Explore how to write functions, including using functions to calculate formulas, getting string and numeric input, and writing formatted output.

This chapter is from the book

### This chapter is from the book 

Programming is like writing a script, creating a predetermined list of words and actions for actors to perform night after night. A Python function is not so different. From within the interactive environment, you can execute a function as often as you like, and it will execute the same predefined “script.” (The term script can also refer to an entire program.)

Within the Python interactive development environment (IDLE), writing functions is the beginning of true programming. In this chapter, I explore how to write functions, including the following:

Using functions to calculate formulas

Getting string and numeric input

Writing formatted output

## Temperatures Rising?

I happen to live in the Northwest corner of the United States, and I have Canadian relatives. When they discuss the weather, they’re always talking Celsius. They might say, “Temperature’s all the way up to 25 degrees. Gettin’ pretty warm, eh?”

For people accustomed to the Fahrenheit scale, 25 is cold enough to freeze your proverbial hockey stick. So I have to mentally run a conversion.

`fahr = cels * 1.8 + 32`

If you have the Python interactive environment running, this is an easy calculation. I can convert 20 degrees in my head, but what about 25? Let’s use Python! The following statements assign a value to the name cels (a variable), use that value to assign another value to the name fahr, and then finally display what the fahr value is.

`>>>cels = 25>>>fahr = cels * 1.8 + 32>>>fahr77.0`

So, 25 “Canadian” degrees are 77.0 degrees on the “real” (that is, the American) temperature scale. That’s comfortably warm, isn’t it? For those living north of the border, it’s practically blistering.

Python prints the answer with a decimal point: 77.0. That’s because when the interactive environment combined my input with the floating-point value 1.8, it promoted all the data to floating-point format.

Let’s try another one. What is the Fahrenheit value of 32 degrees Celsius? Actually, there’s a faster way to do this calculation. We don’t have to use variables unless we want to do so.

`>>>32 * 1.8 + 32.089.6`

Thirty-two degrees on the Celsius scale is 89.6 Fahrenheit. For a Canadian, that’s practically burning up.

But I’d like to make this calculation even easier. What I’d really like to do is just enter a function name followed by a value to convert.

`>>>convert(32)89.6`

And—here is the critical part—if this function worked generally, as if it were part of Python, I could use it to convert any number from Celsius to Fahrenheit. All I’d have to do is enter a different argument.

`>>>convert(10)50.0>>>convert(20)68.0>>>convert(22.5)72.5`

But Python lets me create my own such function. This is what the def keyword does: define a new function. We could write it this way from within the interactive environment:

`>>>def convert(fahr):    cels = fahr * 1.8 + 32.0    return cels>>>`

Notice that these statements by themselves don’t seem to do anything. Actually, they do quite a bit. They associate the symbolic name convert with something referred to as a callable in Python, that is, a function.

If you display the “value” of the function, by itself, you get a cryptic message.

`>>>convert<function convert at 0x1040667b8>`

This message tells you that convert has been successfully associated with a function. There were no syntax errors; however, runtime errors are always possible.

Not until we execute convert do we know whether it runs without errors. But this is easy. To execute a function, just follow it with parentheses—enclosing any arguments, if any.

`>>>convert(5)41.0`

So, 5 degrees Celsius is actually 41.0 Fahrenheit…cool but not quite freezing.

If you enter this example as shown—using the bold font to indicate what you should type as opposed to what Python prints—and if everything goes right, then congrats, you’ve just written your first Python function!

If instead you get a syntax error, remember that you can easily edit a function by 1) moving the cursor to any line of the function and 2) pressing Enter. The entire function definition will reappear, and you can edit it by moving the cursor up and down. Finally, you can reenter it again. (To reenter, put your cursor on the end of the last line and press Enter twice.)

Before resubmitting the function definition, review the following rules:

The definition of convert is followed by parentheses and the name of an argument. This name stands in for the value to be converted. In this case, the argument name is fahr.

You must type a colon (:) at the end of the first line.

The environment then automatically indents the next lines. Use this indentation. Don’t try to modify it—at least not yet.

The return statement determines what value the function produces.

Remember that in Python all names are case-sensitive.

In the interactive environment, you terminate the function by typing an extra blank line after you’re done.

Let’s take another example. Let’s define another function and this time give it the name inch_to_cent. This function is even simpler than the convert function: it changes inches to centimeters, according to the formula 1 inch = 2.54 centimeters.

`>>>def inch_to_cent(inches):    cent = inches * 2.54    return cent>>>`

As with the earlier function, entering a syntactically correct definition doesn’t immediately do anything, but it does create a callable that you can then use to perform the inches-to-centimeter conversation whenever you want.

Here’s an example:

`>>>inch_to_cent(10)25.4>>>inch_to_cent(7.5)19.05`

Note that the inch_to_cent function definition uses its own variable—a local variable—named cent. Because it is local, it doesn’t affect what happens to any variable named cent outside of the function.

But the use of this variable in this case isn’t really necessary. You could define the same function more succinctly, as follows. But the effect is the same in either case.

`>>>def inch_to_cent(x):    return x * 2.54>>>`

You can conceptualize the action of a function call as follows. Each call to the inch_to_cent function passes a particular value in parentheses. This value is passed to the name x inside the function definition, and the return statement produces the output after operating on the x value passed to it.

Here’s an illustration of how this works:

Remember, a function must be defined before a call to that function is executed.

### InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

## Overview

Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

## Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

### Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

### Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

### Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

### Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

### Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

### Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

## Other Collection and Use of Information

### Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

### Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

### Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

### Do Not Track

This site currently does not respond to Do Not Track signals.

## Security

Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

## Children

This site is not directed to children under the age of 13.

## Marketing

Pearson may send or direct marketing communications to users, provided that

• Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
• Such marketing is consistent with applicable law and Pearson's legal obligations.
• Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
• Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

## Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

## Choice/Opt-out

Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

## Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

## Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

## Sharing and Disclosure

Pearson may disclose personal information, as follows:

• As required by law.
• With the consent of the individual (or their parent, if the individual is a minor)
• In response to a subpoena, court order or legal process, to the extent permitted or required by law
• To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
• In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
• To investigate or address actual or suspected fraud or other illegal activities
• To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
• To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
• To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.