Chapter 3 starts getting into some fun exercises (by the way, “Introduction to Computing Using Python…”, this is an excellent book on learning Python as well as learning computer programming.)

Exercise: “Write a function that calculates the perimeter of a circle if you pass in the radius…”

My solution:

import math
def perimeter(x):
    return math.pi * (2*x)

Exercise: “Output numbers in a range from 1 to 12, only returning numbers divisible by 5”

My solution:

z = 0
while z < 12:
    if z % 5 == 0:
    z += 1

Exercise: "Write function negatives() that takes a list as input and prints, one per line, the negative values in the list."

My solution was to use a for loop and an if condition. I used *x as the parameter, which expects a list:

def negatives(*x):
    for i in x[0]:
        if i < 0:


This returns:

Exercise: Make a function called swampFL that takes a list and switches the first and last items in the list.

My solution: Admittedly I did some trial and error here. Without an IDE I would have thought x[0] would have pulled in the appropriate index, but I neglected to see that this in fact pulls in the entire list. I used the swap technique in the literature (a, b = b, a) to swap the values of the list.

def swapFL(*x):
    a = x[0][0]
    b = x[0][-1]
    a, b = b, a
    x[0][0] = a
    x[0][-1] = b


No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Comments