Practice Problems - Set 0

These problems are for practice. They are optional, but you are encouraged to complete them and discuss them with members of the course staff during lab and office hours.

Some of these problems will appear on the final exam, and others are very similar to final exam problems. However, not all final exam problems will be telegraphed.

Problems 0 - 2 reference the function definition below.

def converter(x):
    if x < 0:
        return(-1 * x)
    elif x > 1:
        return(x)
    elif x == 0:
        return(1)
    else:
        return(0)

Problem 0

What is printed by the following program?

for j in range(5):
    k = converter(j)
    print(k, end=" ")

Problem 1

What is printed by the following program?

for j in range(7):
    k = j % 3
    m = converter(k)
    print(m, end=" ")

Problem 2

Modify Line 4 of the converter function such that the printed output of:

for j in range(10):
    k = converter(j)
    print(k, end=" ")

is

1 0 2 0 4 0 6 0 8 0

Problem 3

This program intends to print:

1
22
333
for j in range(3):
    print(j * str(j))

It does not produce this output. Rewrite Line 2 so that this output is produced.

Problem 4

Several of these programs produce the same output. Identify them.

A.

print("""You will ride life straight to perfect laughter.
It's the only good fight there is.""")

B.

print("You will ride life straight to perfect laughter.\n")
print("It's the only good fight there is.")

C.

print("You will ride life straight to perfect laughter.\n", end = "")
print("It's the only good fight there is.")

D.

print("You will ride life straight to perfect laughter. ", end = "\n")
print("It's the only good fight there is.")

E.

print("You will ride life straight to perfect laughter.")
print("It's the only good fight there is.")

Problem 5

What is printed by the following program?

for t in range(9):
    if t > 5:
        print(t + 1, end = " ")
    elif t > 8:
        print(t - 2, end = " ")
    else:
        print(t, end = " ")

Problem 6

What is printed by the following program?

for i in range(1,4):
    for j in range(3):
        if i - j == 0:
            print("same", end= " ")
        else:
            print(i - j, end = " ")

Problem 7

Given this program:

for j in range(2, 12):
    print(j // 2, end= " ")

Modify Line 1 such that the output is:

1 2 3 4 5 

Problem 8

Rewrite the function triangle(size) to use two while loops rather than two for loops.

def triangle(size):
    for j in range(size+1):
        for i in range(j):
            print('*', end="")
        print()

Problem 9

Rewrite the function triangle(size) to use one for loop rather than two for loops.

def triangle(size):
    for j in range(size+1):
        for i in range(j):
            print('*', end="")
        print()