Section 3: Parameters, Returns, and Graphics!
Written by Ecy King, Juliette Woodrow, and Brahm Capoor
This section, we'll practice using parameters and returns to pass information between functions. We'll also use our new animation skills to create a "mystery square" that changes colors randomly. We often include more problems on the handout than can be covered in section, so use any problems you don't get to in section as extra practice for Assignment 3!
Here's the starter code project to download. You'll unzip/extract this file and open it in PyCharm just like you do with your assignment starter code.
In Range
In the file in_range.py, implement the function in_range(num, low, high), which takes
in 3 integers as parameters and returns whether num is in
between low and high, inclusive. Here are a few
same runs of the function, which we've included as doctests in the starter code.
def in_range(n, low, high):
"""
>>> in_range(5, 1, 10)
True
>>> in_range(5, 1, 3)
False
>>> in_range(5, 5, 10)
True
"""
After implementing the in_range function, go to main. In main(), implement the functionality that tells a user whether the number they have entered is in range or not.
Note that starter code has been provided to get user input for n, low, and high.
You can run this code with the python3 in_range.py command, or appropriate command on your device. Here is an example of a sample output.
Enter a number: 10
Enter a lower bound: 30
Enter an upper bound 50
10 is not in between 30 and 50
Enter a number: -4
Enter a lower bound: -100
Enter an upper bound: 7
-4 is in between -100 and 7
Enter a number: 5
Enter a lower bound: 10
Enter an upper bound 3
Please make sure the first number is lower than the second
List Problems
The list_problems.py file contains a lot of miscellaneous problems to get us familiar with handling lists. Some of these are:
sum_of_list()
list_average()
double_list()
count_occurrences()
To see if the code you've written works, feel free to run the Doctests.
Mystery Square
In the file mystery_square.py, implement a program that creates a square that randomly changes
color every second. We've provided some constants: SQUARE_SIZE for the dimensions of the
square, DELAY for the number of seconds to pause between each color change,
and COLORS which is a list of colors you should randomly select from.
Here's a good outline for approaching this problem:
- Create a square that's
SQUARE_SIZEpixels in width and height in the center of the screen. You can choose any initial color. - Create an animation loop; within a loop, sleep for
DELAYseconds and then callcanvas.update(). - Select a new color from the list
COLORSeach time you loop. Perhaps this is a good place to employ a helper function, perhapsget_random_color()which returns a random color from your list.
To run this program, enter python3 mystery_square.py in your terminal.