Creating Your First Application

After all this time, you might have started wondering whether you would get to write any code at all in this chapter. The first application won't be very fancy, but it'll be more than a simple Hello World kind of application. You can use any editor that outputs pure text in this section. Notepad will work just fine. Listing 1-1 shows the code you should type in your editor.

LISTING 1-1: A simple first application that multiplies two numbers

Available for def mult(a, b): download on return a * b return a b print('5 * 10 =') print(mult(5, 10)

Just five lines, including the blank line between the function and the main code, are all you need for this example. Functions begin with the def keyword. You then give the function a name, mult in this case, followed by a list of arguments (if any) — a and b for this example.

Don't worry too much about the details of the IronPython language just yet. Part II of the book provides you with a good overview of all the language details. As the book progresses, you'll be exposed to additional language details. By the time you reach the end of the book, you'll be working with some relatively complex examples.

The content of the function is indented with a tab. In this case, the function simply returns the value of multiplying a by b. Except for the indentation requirement, this could easily be a function written in any other language.

The main code section comes next. In this case, the code begins by printing 5 * 10 =. Notice that you enclose the string values in single quotes. The function call ends with an odd-looking comma. This comma tells the interpreter not to add a /n (newline) character after the print() call.

At this point, the code calls print() a second time, but it calls mult() instead of writing text directly. The output of mult() is an integer, which IronPython automatically converts to a string for you and then prints out. You'll find that IronPython does a lot of work for you in the background — dynamically (as explained earlier in the chapter).

Save the code you've typed into Notepad as Make sure you choose All Files in the Save As Type field so that Notepad doesn't add a .txt extension to the output. To execute this example, type IPY at the command line and press Enter. Figure 1-10 shows the output from this quick example.


v C:\WIND0WS\system32\cmd.exe

_ □ X


■ 0255 - Source Code\C)iapter01 >IP¥ HiiFirst „py

Was this article helpful?

0 0

Post a comment