**CS 111 f19 - Lecture 13 Worksheet** --- # Write a program vs write a function Let's say our task is to compute the sum of a list. How would you describe the difference between writing a program to do this and writing a function do to this? Writing a program would get input from the user or read in the list from a file. It would compute the sum and output it, either to the screen or a file. In contrast, a function would take the list as a parameter, compute the sum and return it. # Absolute value of a list Write two versions of a function that takes a list of numbers and returns a list with the absolute value of each of those numbers. The first version should modify the original list. The second version should create a new list. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Python def version1(nums): for i in range(len(nums)): nums[i] = abs(nums[i]) # modifies the original list return nums def version2(nums): new_nums = [] for num in nums: new_nums.append(abs(num)) return new_nums ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +++++ # Diamonds Write code that given a variable `n`, prints out a diamond `2*n + 1` stars tall. For example, `n = 3` would print out this:
```   *
***
*****
*******
*****
***
*
```
and `n = 5` would print
```     *
***
*****
*******
*********
***********
*********
*******
*****
***
*
```
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Python n = 5 # works for any value of n for i in range(n): line = "" spaces = "" for x in range(n - i): spaces = spaces + " " for x in range(2 * i + 1): line = line + "*" line = spaces + line + spaces print(line) line = "" for x in range(2 * n + 1): line = line + "*" print(line) for i in range(n): line = "" spaces = "" for x in range(i + 1): spaces = spaces + " " for x in range(2 * (n - i) - 1): line = line + "*" line = spaces + line + spaces print(line) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~