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…”
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”
z = 0 while z < 12: if z % 5 == 0: print(z) 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: if i < 0: print(i) negatives([4,0,-1,-3,6,-9])
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 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 b = x[-1] a, b = b, a x = a x[-1] = b print(x) swapFL(['apples','berries','strawberries','bread'])