Writing multiline programs in interactive mode

You can write multiline programs or parts of programs in interactive mode. However, note that interactive mode doesn't let you save your work, so you might also want to save the code in a text file.

The following example program prints some kilometer/mile conversions. Here's how it looks when typed into a text editor. (If you don't understand everything the code does, don't worry. String formatting is explained in Chapter 6.)

print "%d miles --> %3.2f kilometers" % (miles, km)

Note that some lines are indented. Indentation is very important in Python because it's how Python tells when you are using a code block (several lines of code that are grouped together). Four spaces is standard for one level of indentation (the lines starting with km and print), eight spaces for two levels, and so on.

Here's how the same program looks when you start to type it in interactive mode. When you press Return after the first line, the interpreter recognizes that you're writing a code block and displays a continuation prompt: ... (three dots). Even though you see a continuation prompt, you still need to indent the lines that are part of the code block, so don't forget to add four spaces before starting the km assignment and the print statement.

>>> for miles in range(10, 70, 10): ... km = miles * 1.609

... print "%d miles --> %3.2f kilometers" % (miles, km)

Tip Okay, we admit it: We sometimes make our thumbs happier by adding only two spaces when we're working in interactive mode. For actual programs that others might see, though, it's a Good Idea to use four spaces.

When you are finished with the code block, you press Return at the continuation prompt without typing anything. The interpreter runs the code, which gives this result:

10

miles

— >

16

. 09

kilometers

20

miles

— >

32

18

kilometers

30

miles

— >

48 .

.27

kilometers

40

miles

— >

64

36

kilometers

50

miles

— >

80

45

kilometers

60

miles

— >

96.

54

kilometers

When you run a code block in interactive mode, the names you've defined in the namespace retain the values they were given last.

Was this article helpful?

0 0

Post a comment