Week 1: Exercise Solutions

Exercise 1.1

>>> x = 5
>>> y = 8
>>> z = x
>>> x = y
>>> y = z
>>> print("x =", x, " and y =", y)

Exercise 1.2

>>> first_name = "John"
>>> last_name = "Cleese"
>>> print("Hello", first_name, last_name)

Exercise 1.3

# To greet you a number of times
name = input("What is your name? ")
n = int(input("How many times shall I greet you? "))
count = 1
while count <= n:
    print("Hello", name)
    count = count + 1

Exercise 1.4

The second triangular number is 1 + 2 = 3 and the third triangular number is 1 + 2 + 3 = 6.

# To calculate the nth triangular number
n = int(input("Enter n to find the nth triangular "
              "number: "))
triangular = 0
i = 1
while i <= n:
    triangular = triangular + i
    i = i + 1
print("The answer is", triangular)

The formula for the nth triangular number is n(n+1)/2.