Python exercises

Dr. Huidae Cho
Institute for Environmental and Spatial Analysis...University of North Georgia

1   Arithmetic calculator

Keywords: keyboard input, looping, slicing, branching

Write a simple calculator that supports four basic arithmetic operations (+, -, *, and /) for two floating-point numbers.

  1. Print “? ” and read an expression
  2. If the expression is quit, stop
  3. Split the expression into three parts: left operand, operator, and right operand
  4. Branch based on the operator
  5. Calculate the expression and print its result
  6. Go to step 1

2   Dice rolling

Keywords: keyboard input, probability, random()

Python provides a pseudo-random number generator in the random module. We’ll use the random() function from this module to write a dice rolling simulator. This function takes no arguments and returns a pseudo-random float between $[0,1)$. That is, $0\le\text{random()}<1$. The workflow of this program should be as follows:

  1. Print “Roll? ” and read a string input
  2. If the input is quit, stop
  3. Take a random number from random()
  4. Print one of 1–6 based on the random number from step 3
  5. Go to step 1

Do NOT use randint(). Only use these three functions: random(), print(), and input().

3   Quiz: Number guessing

Keywords: keyboard input, probability, randint()

Use the randint() function from the random module to play the number guessing game. The workflow should be as follows:

  1. Generate a new random integer in $[1, 100]$
  2. Print “Guess? ” and read a string input
  3. If the input is quit, stop
  4. If the input is answer, just print your number and go to step 1
  5. If the input matches your number, print You got it and go to step 1
  6. If the input is less than your number, print Your guess is less than mine and go to step 2
  7. If the input is greater than your number, print Your guess is greater than mine and go to step 2

4   HTTP client

Keywords: http, http.client, open

Write a simple HTTP client that downloads and saves it as

5   Recursive factorial

Write a factorial function that recursively calls itself to calculate and return the factorial of an integer. \begin{align*} n!&=n\times(n-1)!\\ 0!&=1 \end{align*}

6   Circle equation

Keywords: math

The following is an equation of a circle with radius $r$ centered at $(0,0)$ in an $x$-$y$ plane: \[x^2+y^2=r^2.\]

  1. Express this equation in radius $r$ and angle $\theta$.
  2. Write a function that returns $y$ when $r$ and $x$ are passed to it as arguments.
  3. Write a function that returns $r$ and $\theta$ when $x$ and $y$ are given.

7   Draw circles

Keywords: turtle, tkinter

Draw a circle using trigonometry and the turtle module.

Draw a circle using trigonometry and the tkinter module.

8   Read and write GeoTIFF files

Keywords: matplotlib.pyplot, PIL.Image

  1. Read elevation.tif in and plot it.
  2. Save the GeoTIFF file as elevation_new.tif and compare the original and new files.
  3. Calculate its extent using TIFF tags

9   Moving average

Keywords: numpy, matplotlib.pyplot, PIL.Image

  1. Read elevation.tif in as a numpy array
  2. Calculate the moving average of nine neighbor cells
  3. Create movavg.tif with the moving average result

10   Read and write shapefiles

Keywords: geopandas, shapely

Read and plot boundary_county.shp, roadsmajor.shp, and schools_wake.shp in Create new shapefiles polys.shp, lines.shp, and points.shp with some geometries.

11   Vector analysis

Keywords: geopandas, shapely

  1. Create 500-meter buffers around schools_wake.shp in
  2. Clip roadsmajor.shp in to the buffers
  3. Select the roadsmajor features that intersect with the school buffers
  4. Save both results into new shapefiles roads_clip.shp and roads_sel.shp, respectively
  5. Plot the roads, school buffers, schools, selected roads, and clipped roads in this order

12   EarthExplorer client

Keywords: json

Sign up for a USGS EarthExplorer account and write a script that can download data using their JSON API.

  1. Send a JSON request using the POST method for retreiving an API key
  2. Parse the JSON response to extract the API key
  3. Send JSON requests using the GET method for downloading your data

13   Conway’s game of life

Keywords: matplotlib.animation.FuncAnimation

Write Conway’s game of life.

14   Moving ball

Keywords: tkinter

  1. Draw a blue ball
  2. Make the ball move in a diagonal direction
  3. Allow it to bounce off of the walls
  4. Control the ball using the arrow keys

15   Quiz: Average elevation

Keywords: matplotlib.pyplot, PIL.Image, geopandas, shapely

In this analysis, we want to calculate the average elevation of a certain census tract.

  1. Read elevation.tif and census_wake2000.shp in
  2. Plot elevation.tif and overlay census_wake2000.shp
  3. Calculate the average elevation of the census tract 25
  4. Print its result using the format f'Tract ID:\t{tract_id}\nCount:\t\t{count}\nTotal:\t\t{total}\nAverage:\t{total/count}'

16   Quiz: GeoTIFF plotting function

Keywords: gdal, matplotlib.pyplot

Use the gdal and matplotlib.pyplot modules to define a function called plot_geotiff that does the following:

  1. Take two arguments: filename for a GeoTIFF path and band for a band to plot
  2. Open the file using gdal.Open
  3. Extract the specified band using GetRasterBand
  4. Read the band as an array using ReadAsArray
  5. Plot the array in memory using plt.imshow
  6. Show the plot using

Please use elevation.tif for testing your script. In your submission, you should have one function named plot_geotiff and a couple lines to call this function for testing. Just submit your Python script without elevation.tif.