{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Python Exercises - Session 3: Control Flow & Strings\n",
"The exercises below are organized to match [A Whirlwind Tour of Python (VanderPlas)](http://www.oreilly.com/programming/free/files/a-whirlwind-tour-of-python.pdf). Specific pages are referenced in the various sections. These are designed to run using Python 3.6.\n",
"\n",
"Follow the guidelines below. Where necessary replace the ellipses (`...`) with the appropriate code in the code blocks, the run the code by pressing ctrl-enter. Be sure to save your document before closing. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"### 3.1 Conditional Statements: `if`, `elif`, and `else` ([p 38](http://nbviewer.jupyter.org/github/env859/WhirlwindTourOfPython/blob/master/07-Control-Flow-Statements.ipynb))\n",
"##### What to know\n",
"* Using the `if` statement to control what code gets run\n",
" * Use of the colon, Boolean condition, and indentation to control execution\n",
" * How `elif` can be used to add more conditional code blocks\n",
" * How `else` can be used to run code when all the `if`'s and `elif`'s are not met. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### ► 3.1.1 Modify the code below so it works to print `too slow`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"avg_speed = 10\n",
"if avg_speed is less than 15, then print \"too slow\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### ► 3.1.2 Write a series of `if`/`elif`/`else` statements that evaluates the value of `elev_feet` such that:\n",
"* If `elev_feet` is less than 400, it prints \"too low\"\n",
"* If `elev_feet` is greater than 500, it prints \"too high\"\n",
"* If `elev_feet ` equal 450, it print \"got it!\"\n",
"* If none of the above conditions are met, it prints \"close enough\"\n",
"* Print \"Play again?\" after evaluating the \"elev_feet\" value"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"elev_feet = 475\n",
"if elev_feet…\n",
" print('too low')\n",
" \n",
" print('too high')\n",
" \n",
" print('got it!')\n",
" \n",
" print('close enough')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"### 3.2 `for` loops ([p 38](http://nbviewer.jupyter.org/github/env859/WhirlwindTourOfPython/blob/master/07-Control-Flow-Statements.ipynb))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**3.2.1** Create a for loop that iterates through the items in the list of states and prints them."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"states = ['Maine','Ohio','Kansas','Utah','Alaska','Nevada']\n",
"for...\n",
" print(state)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**3.2.2** Combine a `for` loop and the `range` function to print powers of 2 up to the 8th power of 2 (256)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for x...\n",
" print(x, 2**x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**3.2.3** *The first line in the code below reads in the contents of the NC_Providers.csv file and stores each line as item in the list `lineList`.* Iterate through the lines in the `lineList` list and print the length of each line.\n",
" * Try using the optional parameter `end` in the print statement so no 'new line' character is printed:
`print(lineText,end='')`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"lineList = open('NC_SiteData.csv','r').readlines()\n",
"for...\n",
" print(...)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**3.2.4** Extact the 10th line from the lineList to a variable called `line10`. Then use the string `split()` method to break this line up into a new list called `lineData`. *(Note that this is a `csv` file, so values are separated by a comma.)* Finally print each of these items, one at a time."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"line10 = lineList[...]\n",
"lineData = line10.split(...)\n",
"for...\n",
" print(...)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"### 3.3 Iterator and the `range()` function ([p52](https://nbviewer.jupyter.org/github/env859/WhirlwindTourOfPython/blob/master/10-Iterators.ipynb#Iterators))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**3.3.1** Print the phrase \"Python is fun!\" 5 times using the `range()` function and a `for` loop."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for...\n",
" print(\"Python is fun!\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**3.3.2** Using the `range()` function in a `for` loop, print the every number between 480 and 490."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for ...\n",
" print (i, end=', ')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**3.3.3** Using the `range()` function in a `for` loop, print every *other* number between 480 and 490. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for ...\n",
" print (i, end=', ')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"### 3.4 `while` loops ([p 39](http://nbviewer.jupyter.org/github/env859/WhirlwindTourOfPython/blob/master/07-Control-Flow-Statements.ipynb))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**3.4.1** Write a `while` loop that prints each year, starting at 2017, stops after printing *2020*"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"year = 2016\n",
"while...\n",
" print(year)\n",
" ..."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**3.4.2** The Python `input` function prompts the user to enter a value. Use a while loop to continue asking the user to \"pick a number between 1 and 4\" until the user guesses correctly."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"guess = input(\"Guess my number, between 1 and 4: \")\n",
"actual_number = \"1\"\n",
"while...\n",
" if...\n",
" guess = input(\"Nope, guess again: \")\n",
"print (\"Got it!, It was \" + actual_number)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 3.5 `break` and `continue`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#Run this to generate a dictionary of states (keys) and their capitol (values)\n",
"state_capitals={\"Washington\":\"Olympia\",\"Oregon\":\"Salem\",\n",
" \"California\":\"Sacramento\",\"Ohio\":\"Columbus\",\n",
" \"Nebraska\":\"Lincoln\",\"Colorado\":\"Denver\",\n",
" \"Michigan\":\"Lansing\",\"Massachusetts\":\"Boston\",\n",
" \"Florida\":\"Tallahassee\",\"Texas\":\"Austin\",\n",
" \"Oklahoma\":\"Oklahoma City\",\"Hawaii\":\"Honolulu\",\n",
" \"Alaska\":\"Juneau\",\"Utah\":\"Salt Lake City\",\n",
" \"New Mexico\":\"Santa Fe\",\"North Dakota\":\"Bismarck\",\n",
" \"South Dakota\":\"Pierre\",\"West Virginia\":\"Charleston\",\n",
" \"Virginia\":\"Richmond\",\"New Jersey\":\"Trenton\",\n",
" \"Minnesota\":\"Saint Paul\",\"Illinois\":\"Springfield\",\n",
" \"Indiana\":\"Indianapolis\",\"Kentucky\":\"Frankfort\",\n",
" \"Tennessee\":\"Nashville\",\"Georgia\":\"Atlanta\",\n",
" \"Alabama\":\"Montgomery\",\"Mississippi\":\"Jackson\",\n",
" \"North Carolina\":\"Raleigh\",\"South Carolina\":\"Columbia\",\n",
" \"Maine\":\"Augusta\",\"Vermont\":\"Montpelier\",\n",
" \"New Hampshire\":\"Concord\",\"Connecticut\":\"Hartford\",\n",
" \"Rhode Island\":\"Providence\",\"Wyoming\":\"Cheyenne\",\n",
" \"Montana\":\"Helena\",\"Kansas\":\"Topeka\",\n",
" \"Iowa\":\"Des Moines\",\"Pennsylvania\":\"Harrisburg\",\n",
" \"Maryland\":\"Annapolis\",\"Missouri\":\"Jefferson City\",\n",
" \"Arizona\":\"Phoenix\",\"Nevada\":\"Carson City\",\n",
" \"New York\":\"Albany\",\"Wisconsin\":\"Madison\",\n",
" \"Delaware\":\"Dover\",\"Idaho\":\"Boise\",\n",
" \"Arkansas\":\"Little Rock\",\"Louisiana\":\"Baton Rouge\"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**3.5.1** Use a `for` loop and a `break` statement to iterate through states (i.e., the keys) in the `state_capitals` dictionary, printing the name of the state's capitol, stopping when 'Texas' is reached (and not printing Texas' capitol). "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#Loop through the keys in the dict (i.e. states)\n",
"for … in state_capitals.keys(): \n",
" #Use an if statement to determine if the current state is 'Texas'\n",
" if …: \n",
" #If so, stop iterating immediately\n",
" …\n",
" # Print the dictionary value corresponding with the state\n",
" print(…)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**3.5.2** Modify the `if` statment and swap the `break` statement with `continue` so that instead of stopping at Texas, the loop **skips** printing the capital of any state ending with the letter `a`. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#Loop through the keys in the dict (i.e. states)\n",
"for … in state_capitals.keys(): \n",
" #Get the capital associated from the current state key\n",
" capital = ...\n",
" #If the capital ends with 'a'...\n",
" if …: \n",
" #...skip the remainder of the 'for loop' for this iteration \n",
" # and move forward to the next item in the list \n",
" …\n",
" # Print the dictionary value corresponding with the state\n",
" print(…)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 6. String Manipulation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**3.6.1** Create a new variable called \"all_sports_lower\" that has the contents of the `all_sports` string, but using all lowercase letters."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#Create the initial string\n",
"all_sports = \"Soccer, BASKETBALL, Hockey, Tennis\"\n",
"all_sports_lower = …\n",
"print(all_sports_lower)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**3.6.2** Use the `split()` function to parse the string into a list variable named \"sports\". "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sports = all_sports_lower.…\n",
"print(sports)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**3.6.3** Tweak the code below to print Euler's number ($e$) to 6 decimal places."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"e = 2.71828182845904\n",
"print(…)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**3.6.4** Use the variables below to print out the address so it appears as:\n",
"```\n",
"222 Main St.\n",
"Durham, NC 27701\n",
"```\n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"house_number = 222\n",
"street_name = \"Main st.\"\n",
"city = \"Durham\"\n",
"state = \"NC\"\n",
"zip = 27701\n",
"\n",
"print(…)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.10"
}
},
"nbformat": 4,
"nbformat_minor": 2
}