# Python exercises

- 1 Arithmetic calculator
- 2 Dice rolling
- 3 Quiz: Number guessing
- 4 HTTP client
- 5 Recursive factorial
- 6 Circle equation
- 7 Draw circles
- 8 Read and write GeoTIFF files
- 9 Moving average
- 10 Read and write shapefiles
- 11 Vector analysis
- 12 EarthExplorer client
- 13 Conway’s game of life
- 14 Moving ball
- 15 Quiz: Average elevation
- 16 Quiz: GeoTIFF plotting function

## 1 Arithmetic calculator

**Keywords:**keyboard input, looping, slicing, branching

**simple_calculator.py**

Write a simple calculator that supports four basic arithmetic operations (`+`

, `-`

, `*`

, and `/`

) for two floating-point numbers.

- Print “
`?`

” and read an expression - If the expression is
`quit`

, stop - Split the expression into three parts: left operand, operator, and right operand
- Branch based on the operator
- Calculate the expression and print its result
- Go to step 1

## 2 Dice rolling

**Keywords:**keyboard input, probability,

`random()`

**dice_rolling.py**

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:

- Print “
`Roll?`

” and read a string input - If the input is
`quit`

, stop - Take a random number from
`random()`

- Print one of 1–6 based on the random number from step 3
- 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()`

**FirstLastname_number_guessing.py**

Use the `randint()`

function from the `random`

module to play the number guessing game. The workflow should be as follows:

- Generate a new random integer in $[1, 100]$
- Print “
`Guess?`

” and read a string input - If the input is
`quit`

, stop - If the input is
`answer`

, just print your number and go to step 1 - If the input matches your number, print
`You got it`

and go to step 1 - If the input is less than your number, print
`Your guess is less than mine`

and go to step 2 - 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

**http_client.py**

Write a simple HTTP client that downloads https://prd-tnm.s3.amazonaws.com/StagedProducts/Elevation/13/ArcGrid/USGS_NED_13_n34w085_ArcGrid.zip and saves it as USGS_NED_13_n34w085_ArcGrid.zip.

## 5 Recursive factorial

**factorial.py**

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

**circle.py**

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.\]

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

## 7 Draw circles

**Keywords:**turtle, tkinter

**turtle_circle.py**

Draw a circle using trigonometry and the turtle module.

**tkinter_circle.py**

Draw a circle using trigonometry and the tkinter module.

## 8 Read and write GeoTIFF files

**Keywords:**matplotlib.pyplot, PIL.Image

**tiff_read_write.py**

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

## 9 Moving average

**Keywords:**numpy, matplotlib.pyplot, PIL.Image

**moving_average.py**

- Read elevation.tif in nc_spm_08_grass7_exercise.zip as a numpy array
- Calculate the moving average of nine neighbor cells
- Create movavg.tif with the moving average result

## 10 Read and write shapefiles

**Keywords:**geopandas, shapely

**shapefile_read.py**

Read and plot boundary_county.shp, roadsmajor.shp, and schools_wake.shp in nc_spm_08_grass7_exercise.zip.

**shapefile_write.py**
Create new shapefiles polys.shp, lines.shp, and points.shp with some geometries.

## 11 Vector analysis

**Keywords:**geopandas, shapely

**vector_analysis.py**

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

## 12 EarthExplorer client

**Keywords:**json

**earthexplorer_client.py**

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

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

## 13 Conway’s game of life

**Keywords:**matplotlib.animation.FuncAnimation

**game_of_life.py**

Write Conway’s game of life.

## 14 Moving ball

**Keywords:**tkinter

**moving_ball.py**

- Draw a blue ball
- Make the ball move in a diagonal direction
- Allow it to bounce off of the walls
- Control the ball using the arrow keys

## 15 Quiz: Average elevation

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

**FirstLastname_average_elevation.py**

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

- Read elevation.tif and census_wake2000.shp in nc_spm_08_grass7_exercise.zip
- Plot elevation.tif and overlay census_wake2000.shp
- Calculate the average elevation of the census tract 25
- 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

**FirstLastname_geotiff_plotter.py**

Use the gdal and matplotlib.pyplot modules to define a function called `plot_geotiff`

that does the following:

- Take two arguments:
`filename`

for a GeoTIFF path and`band`

for a band to plot - Open the file using
`gdal.Open`

- Extract the specified band using
`GetRasterBand`

- Read the band as an array using
`ReadAsArray`

- Plot the array in memory using
`plt.imshow`

- Show the plot using
`plt.show`

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.