Problems regarding 'if' statements, 'for' loops, 'while' loops


What does the following Python program output?

if 1+2*3 > 8:
    print 'yes'
    if 3+4 < 5:
        print 'definitely'
    else:
        print 'possibly'
else:
    print 'no'
    if 1 < 2:
        print 'seriously'
    else:
        print 'don\'t even ask'
if 1 < 2:
    print 'really'
else:
    print 'like whatever'
[Solution: Try it! And then if you're not sure why it's doing what it's doing, work on it, and ask me or a TA if you need help.]


Write a python program which prompts for and inputs someone's name and age; then if the age is 18, print "Happy birthday, name!", using the name they specified. (If the age is not exactly 18, there is no further output.)

[solution]


a) Write a Python program to print the integers (whole numbers) from 10 to 20, inclusive, using a loop.

b) Write a Python program to prompt the user for their name and then say "hello" using their name (e.g. "Hello, Alan").

c) What does the following Python program output?

        x = 3
        y = x + x
        y = y + y
        y = x + y
        print y

d) What does the following Python program output?

        x = 2
        while x < 30:
            x = x * 5
        print x

e) What does the following Python program output?

        for i in range(2,5):
            print 'z' * i

[solutions]


State the output from each of these Python programs:

(a)

        x = 3
        y = 5
        print 'x'

(b)

        sum = 0
        for i in range(2,5):
            sum = sum + i
        print sum

(c)

        sum = 0
        for i in range(2,5):
            sum = sum + i
            print sum

(d)

        x = 2
        while x < 10:
            x = x * 2
        print x

[Solutions: Just run the thing and see! But as with all of these problems, please try working it out before you look at the answer.]


[index of CSC 104 test problem categories]
[main course page]