Python training exercise 2

From BITS wiki
Jump to: navigation, search

Introduction

Just printing things is not that interesting, what you really want to do with a computer program is manipulate data. This is why variables are so important - they allow you to assign information to a name that you can re-use later on.

In this section we will introduce the basic types of variables and how you can manipulate them.

Exercises

Formatting the output

It is also possible to format the output when using the print command.

print("My name is {}.".format("Jane"))

The above don't do anything interesting; you can however put a number in between the '%' and 's' to force the output to take up a number of characters. Try this:

print("My name is {:>10}.".format("Jane"))

You'll now see that you force an area of 10 characters to put the name. Note that the > character in the .format() form can be used to determine the alignment (use < for left align, = for centered).

In Python2.5 and older, you use the %s formatting character to position the information in the right place. Here's the above examples using that syntax:

print("My name is %s." % "Jane")
print("My name is %10s." % "Jane")

If you use formatting characters and you want to print a percentage sign in the old form, you have to use %%:

print("This is a %% %s." % "sign")

This is trivial in the new form:

print("This is a % {}.".format("sign"))

Formatting numbers

Here are some examples of formatting integers (digits):

print(“This is {:d}.”.format(25))
 
print(“This is {:d} and {:d}.”.format(25,30))

Here are some examples of formatting decimal number (floating point):

myFloat = 4545.4542244
 
print("Print the full float {},\ncut off decimals {:.2f},\nor determine the characters before the decimal {:10.1f}.”.format(myFloat,myFloat,myFloat))
 
# Or in old style
 
print("Print the full float %f,\ncut off decimals %.2f,\nor determine the characters before the decimal %10.1f." % (myFloat,myFloat,myFloat))

Special characters

For some characters it is necessary to use what are called 'escape' codes because you cannot type the character normally from the keyboard. Try this:

print("The \\ sign\ncan\talso\tbe\tprinted.")

Here the \\ will print a backslash (otherwise Python will think you are trying to insert a special code), the \n will print a new line, \t a tab character.

Escape codes are also necessary if you are trying to print a single or double quote:

print("He said: \"Hello\".")


Back to main page