Discussion - Friday, 2/18/2011

Topics: Format strings, escape sequences, loops
Complete the exercises at the end of this document!


Formatting Strings:
Controlling the appearance of output in print statements

Format strings for different types:
%f -- used for floating point numbers
%e and %E -- used for floating point numbers in exponential form
%d -- used for integers
%s -- used for strings

Example with floating point numbers:
print "%.2f and %.4f are my favorite numbers!" % (3.14159, 2.71835)

Output:
3.14 and 2.7184 are my favorite numbers!

Note: For the two values in the above example, we are printing:


Example with integers and strings:
print '%s is %d years old' % ('Elvis', 25)

Output:
Elvis is 25 years old




Loop Review


while loops:
while <some condition>:
        statement
        statement
        ...
        statement

Example:
number = 10
while number >= 7:
        print number
        number = number - 1

What is the output??


for loops
for i in sequence:
        statement
        ...
        statement

Note: Execute the body of the loop once for each value of i in the sequence.

Example:
for i in [1, 2, 3]:
        print i

What is the output?

Example:
sum = 0
for i in range(1, 5):
        sum = sum + i
print 'The sum is %d.' % sum

Output?



Escape Sequences

Use escape sequences inside quotes in print statements: these 2 character sequences start with a backslash.

\t -- tab
\n -- carriage return
\\ -- display a backslash

Example:
print 'Hello\n\tworld'

Output:
Hello
      world


Exercises:

1. Write a program that uses a for loop to compute the sum of the even integers from 12 to 100.

2. Read two numbers from the user, and print their sum. Note that you must use a format string to produce the output.
Sample Run:
First number? 10
Second number? 12
The sum is 22.

3. Use a while loop to print 99, 96, 93, ..., 3 in this order to the screen, one number per line.

4. Write a function make10 that, given two ints a and b, prints True if one of them is 10 or if their sum is 10.

def make10(a, b):
    # finish the function definition