15.04.2018 Views

programming-for-dummies

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

220<br />

Passing Parameters<br />

This BASIC language example defines a subprogram named PrintMyName,<br />

which accepts two parameters. The first parameter is an integer variable —<br />

PrintTimes — which defines how many times to print a name.<br />

The second parameter is a string variable — Name — which defines the<br />

name to print multiple times.<br />

Every <strong>programming</strong> language offers slightly different ways of creating a subprogram.<br />

Here’s what an equivalent Python subprogram might look like:<br />

def print_my_name(printtimes, name):<br />

<strong>for</strong> i in range(printtimes):<br />

print name<br />

By writing a generic subprogram that accepts parameters, you can create a<br />

single subprogram that can behave differently, depending on the parameters<br />

it receives.<br />

To give or pass parameters to a subprogram, you need to call the subprogram<br />

by name along with the parameters you want to give that subprogram.<br />

So if a subprogram accepted two parameters (an integer and a string), you<br />

could call that subprogram by doing the following:<br />

PrintMyName (5, “John Smith”)<br />

PrintMyName (16, “Mary Jones”)<br />

The first command tells the PrintMyName subprogram to use the number 5<br />

and the string John Smith as its parameters. Because the number defines<br />

how many times to print and the string defines what to print, this first command<br />

tells the PrintMyName subprogram to print John Smith five times.<br />

The second command tells the PrintMyName subprogram to use the<br />

number 16 and the string Mary Jones as its parameters, which prints Mary<br />

Jones 16 times, as shown in Figure 6-5.<br />

Calling a subprogram works the same way in other <strong>programming</strong> languages.<br />

So if you want to call the following Python subprogram:<br />

def print_my_name(printtimes, name):<br />

<strong>for</strong> i in range(printtimes):<br />

print name<br />

You could print the name John Smith four times with this command:<br />

print_my_name(4, “John Smith”)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!