Lab: More Loops
Preparation
Create a file called loops.py
and put the functions you write inside this file. This will allow you to easily run these functions from the terminal for testing purposes.
Exercise 1
Write a function named print_triangle.py(num)
that takes in a positive integer num
and prints out a right triangle with side length num
. Below are a few example executions.
>>> print_triangle(5)
* * * * *
* * * *
* * *
* *
*
>>> print_triangle(3)
* * *
* *
*
Remember that this function is printing the output and returns nothing.
Exercise 2
Write a function called simple_file_to_list
that takes a single parameter filename
which is a path to a text file. The file itself may contain any sequence of integers—one integer per line. The function should read all the integers from the file and build a list of all the integers in the file and return the list. For example, consider a file named numbers.txt
that contains the following numbers.
5
7
-13
12
100
-22
If you execute your function it should return:
>>> result = simple_file_to_list("numbers.txt")
>>> print(result)
[5, 7, -13, 12, 100, -22]
Remember that to open up the file and iterate over the lines of the file, you can execute the following:
file = open(filename, 'r')
for line in file:
# CODE GOES HERE
Exercise 3
Using what you learned from the previous exercise, write a function called file_to_list
that takes a single parameter filename
that is the name of a file that contains a sequence of integers separated by spaces and newlines. For example, consider a file named more-numbers.txt
that contains the following numbers.
5 7
-13 12 100
-22
If you execute your function it should return:
>>> result = file_to_list("more-numbers.txt")
>>> print(result)
[5, 7, -13, 12, 100, -22]
Exercise 4
Write a program named repeated_average.py
that does the following indefinitely:
- Prompts the user with a message saying
Enter numbers separated by spaces or "quit" to exit.
- Prints a
>
symbol letting the user know they are being asked to type something. - If they type numbers, it computes the average of the numbers entered and prints them back to the user. If they type
quit
, it exits the program. - Repeat steps 2-4.
$ python3 repeated_average.py
Enter numbers separated by spaces or "quit" to exit.
> 1 2 3 4
2.5
> 7 3
5
> 19 -7 3 -5 10
4
> quit