|
| 1 | +{ |
| 2 | + "cells": [ |
| 3 | + { |
| 4 | + "cell_type": "markdown", |
| 5 | + "id": "8fdc0282-e0c7-4399-ae1e-35c8862df679", |
| 6 | + "metadata": {}, |
| 7 | + "source": [ |
| 8 | + "# Workshop 2 - I/O, Formatting, and Flow Control\n", |
| 9 | + "\n", |
| 10 | + "Welcome to week two! Today we'll be looking at I/O, Formatting, and Flow Control - including what they are, what they're used for, and plenty of practical examples of their use.\n", |
| 11 | + "\n", |
| 12 | + "- [I/O](#I/O)\n", |
| 13 | + " - [Reading Inputs](#Reading-Inputs)\n", |
| 14 | + " - [File Objects](#File-Objects)\n", |
| 15 | + " - [Useful Methods](#Useful-Methods)\n", |
| 16 | + "- [Formatting & Flow Control](#Formatting-&-Flow-Control)\n", |
| 17 | + " - [Formatting](#Formatting)\n", |
| 18 | + " - [Loops](#Loops)\n", |
| 19 | + " - [Statements](#Statements)" |
| 20 | + ] |
| 21 | + }, |
| 22 | + { |
| 23 | + "cell_type": "markdown", |
| 24 | + "id": "8832cbbd-139b-44c9-9260-eae1f443591e", |
| 25 | + "metadata": {}, |
| 26 | + "source": [ |
| 27 | + "## I/O\n", |
| 28 | + "I/O - shorthand for ***Input/Output*** - refers to the action of taking inputs or producing outputs in Python.\n", |
| 29 | + "\n", |
| 30 | + "In terms of inputs, I/O covers implementations as simple as having a user select an option or provide some input text, to as complex as providing multiple different files (e.g. spreadsheets, images, videos, etc). In terms of outputs, I/O covers implementations as simple as providing a boolean result for a given statement, to providing complex graphical or file outputs.\n", |
| 31 | + "\n", |
| 32 | + "We will be walking through reading a variety of different types of input, providing various types of outputs, and showing off a handful of useful methods for working with I/O in your own code." |
| 33 | + ] |
| 34 | + }, |
| 35 | + { |
| 36 | + "cell_type": "markdown", |
| 37 | + "id": "abd43683-5a93-479a-b7c9-1f207ff8eb8d", |
| 38 | + "metadata": {}, |
| 39 | + "source": [ |
| 40 | + "## Reading Inputs\n", |
| 41 | + "\n", |
| 42 | + "One of the most simple ways we can read user input in Python is using the input() function.\n", |
| 43 | + " \n", |
| 44 | + "Using what you learned in this week's lecture, implement a simple program that asks the user for their name and stores that name as a variable." |
| 45 | + ] |
| 46 | + }, |
| 47 | + { |
| 48 | + "cell_type": "code", |
| 49 | + "execution_count": 3, |
| 50 | + "id": "7f24c21b-96bf-4022-a570-84ad90e938dc", |
| 51 | + "metadata": {}, |
| 52 | + "outputs": [], |
| 53 | + "source": [ |
| 54 | + "# hint: use input() to query the user, assigning the output to a variable\n", |
| 55 | + "name = input('What is your name?')" |
| 56 | + ] |
| 57 | + }, |
| 58 | + { |
| 59 | + "cell_type": "markdown", |
| 60 | + "id": "26695d2a-f33d-4ad6-a12a-20ba2b13b706", |
| 61 | + "metadata": {}, |
| 62 | + "source": [ |
| 63 | + "It's important to note that the input() function processed the given response as a string, regardless of what the given input was. With that in mind, expand on your simple program from the previous task with a check for a specific name (maybe use your own name), printing a greeting to the user if they have the correct name." |
| 64 | + ] |
| 65 | + }, |
| 66 | + { |
| 67 | + "cell_type": "code", |
| 68 | + "execution_count": null, |
| 69 | + "id": "a343c6dd-a29c-4971-83d8-c8bcdf274bee", |
| 70 | + "metadata": {}, |
| 71 | + "outputs": [], |
| 72 | + "source": [ |
| 73 | + "# hint: the output of input() is always a string, perform a check for a specific name using the == operator\n", |
| 74 | + "if name == 'James':\n", |
| 75 | + " print('Hi James!')" |
| 76 | + ] |
| 77 | + }, |
| 78 | + { |
| 79 | + "cell_type": "markdown", |
| 80 | + "id": "876f2ea1-720f-4968-aa46-7491690290a5", |
| 81 | + "metadata": {}, |
| 82 | + "source": [ |
| 83 | + "The above was an example of taking a simple text user input, but what if we want to take a file (or files) as an input?" |
| 84 | + ] |
| 85 | + }, |
| 86 | + { |
| 87 | + "cell_type": "markdown", |
| 88 | + "id": "ac79e737-4483-4210-ba53-3d978294b96e", |
| 89 | + "metadata": {}, |
| 90 | + "source": [ |
| 91 | + "### File Objects\n", |
| 92 | + "\n", |
| 93 | + "***File objects*** are objects (don't worry about what those are, we'll get to it!) that represent a local file - this could be a text file, an excel file, or almost any other type of file. These file objects have several built-in methods for interacting with the file they represent.\n", |
| 94 | + "\n", |
| 95 | + "Download the greetings.txt file from Blackboard (and place it into the same folder as this notebook). Read in the file using the with/as syntax covered in the lecture this week. Print the contents of the file using the .read() method. *If you choose not to use the with/as method and instead just call open(), be sure to .close() the file*." |
| 96 | + ] |
| 97 | + }, |
| 98 | + { |
| 99 | + "cell_type": "code", |
| 100 | + "execution_count": 5, |
| 101 | + "id": "307fa78b-1f39-4ce0-8b76-f3eb8bec2875", |
| 102 | + "metadata": {}, |
| 103 | + "outputs": [ |
| 104 | + { |
| 105 | + "name": "stdout", |
| 106 | + "output_type": "stream", |
| 107 | + "text": [ |
| 108 | + "\n" |
| 109 | + ] |
| 110 | + } |
| 111 | + ], |
| 112 | + "source": [ |
| 113 | + "# tip: remember the open() modes are \"rawx\"\n", |
| 114 | + "with open('greetings.txt', 'r') as greetings_file:\n", |
| 115 | + " print(greetings_file.read())" |
| 116 | + ] |
| 117 | + }, |
| 118 | + { |
| 119 | + "cell_type": "markdown", |
| 120 | + "id": "a20964f0-1e18-486e-bb13-ae45cdd51b82", |
| 121 | + "metadata": {}, |
| 122 | + "source": [ |
| 123 | + "We also covered some other built-in methods such as .mode, .name. and read variants like .readline(), but let's look at writing.\n", |
| 124 | + "\n", |
| 125 | + "For the following task, read in the greetings file again and write three more greetings - use a language you're familiar with or just find some online - then read the file in again and print the new contents." |
| 126 | + ] |
| 127 | + }, |
| 128 | + { |
| 129 | + "cell_type": "code", |
| 130 | + "execution_count": 7, |
| 131 | + "id": "607099d8-fd34-4779-a309-2b5f4d121b59", |
| 132 | + "metadata": {}, |
| 133 | + "outputs": [ |
| 134 | + { |
| 135 | + "name": "stdout", |
| 136 | + "output_type": "stream", |
| 137 | + "text": [ |
| 138 | + "merhaba\n", |
| 139 | + "namaste\n", |
| 140 | + "\n" |
| 141 | + ] |
| 142 | + } |
| 143 | + ], |
| 144 | + "source": [ |
| 145 | + "# tip: remember that you need to keep your open() calls separate, one for writing and then one for reading\n", |
| 146 | + "with open('greetings.txt', 'w') as greetings_file:\n", |
| 147 | + " greetings_file.write('merhaba\\n')\n", |
| 148 | + " greetings_file.write('namaste\\n')\n", |
| 149 | + "\n", |
| 150 | + "with open('greetings.txt', 'r') as greetings_file:\n", |
| 151 | + " print(greetings_file.read())" |
| 152 | + ] |
| 153 | + }, |
| 154 | + { |
| 155 | + "cell_type": "markdown", |
| 156 | + "id": "54f2ea55-e386-42be-884a-d596b545de72", |
| 157 | + "metadata": {}, |
| 158 | + "source": [ |
| 159 | + "# Formatting & Flow Control\n", |
| 160 | + "\n", |
| 161 | + "## Formatting\n", |
| 162 | + "Sometimes (in fact, quite often) we want to control how data is displayed when we output it.\n", |
| 163 | + "\n", |
| 164 | + "Create three variables (either integers or floats) and print a full mathematical sum using them, including the result e.g. the output should be \"3 + 5 + 2 = 10\" not simply \"10\"." |
| 165 | + ] |
| 166 | + }, |
| 167 | + { |
| 168 | + "cell_type": "code", |
| 169 | + "execution_count": null, |
| 170 | + "id": "8e19b343-72d0-46e2-b975-2b7b2828eb79", |
| 171 | + "metadata": {}, |
| 172 | + "outputs": [], |
| 173 | + "source": [ |
| 174 | + "# tip: remember, the built-in string method .format() is your friend\n", |
| 175 | + "a = 3\n", |
| 176 | + "b = 5\n", |
| 177 | + "c = 2\n", |
| 178 | + "print('{} + {} + {} = {}'.format(a, b, c, a + b + c))" |
| 179 | + ] |
| 180 | + }, |
| 181 | + { |
| 182 | + "cell_type": "markdown", |
| 183 | + "id": "b9e83ab8-85b3-4f2a-a956-ed1536923c98", |
| 184 | + "metadata": {}, |
| 185 | + "source": [ |
| 186 | + "## Loops\n", |
| 187 | + "\n", |
| 188 | + "Quite often, we will want to ***perform a certain task iteratively***. We could, of course, just type out the task as many times as we want it to execute, but that's ***very inefficient***, ***harms readability***, and ***cannot account for changed inputs*** (we would have to re-write the code dependent on the size of the input). That's where loops come in!\n", |
| 189 | + "\n", |
| 190 | + "For this task, once again ask the user for their name, then read in the greetings.txt file as before. Using a for loop and string formatting, greet the user by their given name using each greeting in the file.\n", |
| 191 | + "\n", |
| 192 | + "Example: \n", |
| 193 | + "salut, James! \n", |
| 194 | + "hola, James! \n", |
| 195 | + "privet, James! \n", |
| 196 | + "and so on" |
| 197 | + ] |
| 198 | + }, |
| 199 | + { |
| 200 | + "cell_type": "code", |
| 201 | + "execution_count": null, |
| 202 | + "id": "8d8db9a6-3a10-4661-99b3-5ccfeaeb6205", |
| 203 | + "metadata": {}, |
| 204 | + "outputs": [], |
| 205 | + "source": [ |
| 206 | + "# tip: you will want to use input(), string formatting, and a for loop for your implementation\n", |
| 207 | + "name = input('What is your name?')\n", |
| 208 | + "with open('greetings.txt', 'r') as greetings_file:\n", |
| 209 | + " for line in greetings_file:\n", |
| 210 | + " print('{}, {}!'.format(line.strip(), name))" |
| 211 | + ] |
| 212 | + }, |
| 213 | + { |
| 214 | + "cell_type": "markdown", |
| 215 | + "id": "e986a6b3-5717-48bd-8b61-256fb7d66a79", |
| 216 | + "metadata": {}, |
| 217 | + "source": [ |
| 218 | + "In other languages, you will see this type of loop separated into two types, either ***for loops*** or ***foreach loops***. Python refers to the type we just discussed as a ***for loop***, but it actually functions like a ***foreach loop*** as in \"for each x in y\"." |
| 219 | + ] |
| 220 | + }, |
| 221 | + { |
| 222 | + "cell_type": "markdown", |
| 223 | + "id": "285b8a3b-a629-4940-82a4-edfe7b595c98", |
| 224 | + "metadata": {}, |
| 225 | + "source": [ |
| 226 | + "## Statements\n", |
| 227 | + "\n", |
| 228 | + "There are a multitude of useful statements we can use to control the way in which a set of code executes – this is called control flow. We’ve already covered for loops and while loops, which are an option, what else is there?\n", |
| 229 | + "\n", |
| 230 | + "Let's take a look at ***if statements***, bringing together everything we've learned so far.\n", |
| 231 | + "\n", |
| 232 | + "Query the user for their name and age. Assuming the user is in the UK, check if they are of the legal driving age (17 or over). Read in the greetings.txt file and include a greeting (use readline) in a print statement telling the user whether or not they are legally allowed to drive. This code should run indefinitely until a user that is old enough to legally drive enters their information.\n", |
| 233 | + "\n", |
| 234 | + "***Note: It is key that you can understand the logic enough to solve this task, if you need help please ask for it - it's imperative you seek help rather than struggling in silence and allowing yourself to fall behind!***" |
| 235 | + ] |
| 236 | + }, |
| 237 | + { |
| 238 | + "cell_type": "code", |
| 239 | + "execution_count": null, |
| 240 | + "id": "e6f36db0-015b-4ec3-ba52-13a9fe527526", |
| 241 | + "metadata": {}, |
| 242 | + "outputs": [], |
| 243 | + "source": [ |
| 244 | + "# tip: you will need a variable for keeping track of whether or not the current user is old enough\n", |
| 245 | + "# you should use that variable in a while loop to allow the code to constantly re-run if the current\n", |
| 246 | + "# user is not old enough to drive, your input() calls should be inside the loop, and you should use\n", |
| 247 | + "# string formatting within the print statements to include the greeting and name.\n", |
| 248 | + "import random\n", |
| 249 | + "\n", |
| 250 | + "\n", |
| 251 | + "with open('greetings.txt', 'r') as greetings_file:\n", |
| 252 | + " greetings = greetings_file.readlines()\n", |
| 253 | + "\n", |
| 254 | + "while True:\n", |
| 255 | + " name = input('What is your name?')\n", |
| 256 | + " age = int(input('How old are you?'))\n", |
| 257 | + " # the random.choice is not strickly needed, you can select on greeting deterministically\n", |
| 258 | + " # string.strip() removes any whitespaces and newlines on the left and right of text\n", |
| 259 | + " greeting = random.choice(greetings).strip()\n", |
| 260 | + " if age >= 17:\n", |
| 261 | + " print('{}, {}! You are old enough to drive!'.format(greeting, name))\n", |
| 262 | + " break # exit the while loop\n", |
| 263 | + " else:\n", |
| 264 | + " print('{}, {}! You are not old enough to drive!'.format(greeting, name))\n", |
| 265 | + " " |
| 266 | + ] |
| 267 | + }, |
| 268 | + { |
| 269 | + "cell_type": "markdown", |
| 270 | + "id": "1a52e54b-6670-446f-bac5-4e61066e1a7d", |
| 271 | + "metadata": {}, |
| 272 | + "source": [ |
| 273 | + "As a final task, take the last exercise from last week's workshop and solve it using conditional statements and I/O functions:\n", |
| 274 | + "\n", |
| 275 | + "*Create a small piece of code that creates three variables representing the current temperature, whether it is sunny or not, and yesterday's probability of raining. Your code need to determine what is the probability of raininig today based on his data. If it is sunny, the probability of rain is fixed at 5%. In case it is not sunny, today's probability sees and increase of 20% compared to yesterday if the temperature is higher than 20 C and a decrease of 45% if the temperature is smaller or equal than 20 C.* " |
| 276 | + ] |
| 277 | + }, |
| 278 | + { |
| 279 | + "cell_type": "code", |
| 280 | + "execution_count": null, |
| 281 | + "id": "bfcce079", |
| 282 | + "metadata": {}, |
| 283 | + "outputs": [], |
| 284 | + "source": [ |
| 285 | + "# Create a dictionary and ask user to provide input data\n", |
| 286 | + "data = {\n", |
| 287 | + " 'current_temperature': int(input(\"Provide current temperature in C: \")),\n", |
| 288 | + " 'sunny': bool(input(\"Insert 1 if it is currently sunny, 0 otherwise: \")),\n", |
| 289 | + " 'yesterday_p_rain': int(input(\"Provide yesterday's probability of rain as an int (e.g., 20 for %20): \"))\n", |
| 290 | + "}\n", |
| 291 | + "\n", |
| 292 | + "\n", |
| 293 | + "if data['sunny']:\n", |
| 294 | + " # if it is sunny the probability is fixed at 5%\n", |
| 295 | + " data['today_p_rain'] = 5\n", |
| 296 | + "elif data['current_temperature'] > 20:\n", |
| 297 | + " # increase by 20% compared to yesterday\n", |
| 298 | + " data['today_p_rain'] = data['yesterday_p_rain'] + (data['yesterday_p_rain'] * 0.2)\n", |
| 299 | + "else:\n", |
| 300 | + " # decrease by 45% compared to yesterday\n", |
| 301 | + " data['today_p_rain'] = data['yesterday_p_rain'] - (data['yesterday_p_rain'] * 0.45)\n", |
| 302 | + "\n", |
| 303 | + "\n", |
| 304 | + "print(\"Today's probability of rain is {}\".format(data['today_p_rain']))" |
| 305 | + ] |
| 306 | + } |
| 307 | + ], |
| 308 | + "metadata": { |
| 309 | + "kernelspec": { |
| 310 | + "display_name": "Python 3 (ipykernel)", |
| 311 | + "language": "python", |
| 312 | + "name": "python3" |
| 313 | + }, |
| 314 | + "language_info": { |
| 315 | + "codemirror_mode": { |
| 316 | + "name": "ipython", |
| 317 | + "version": 3 |
| 318 | + }, |
| 319 | + "file_extension": ".py", |
| 320 | + "mimetype": "text/x-python", |
| 321 | + "name": "python", |
| 322 | + "nbconvert_exporter": "python", |
| 323 | + "pygments_lexer": "ipython3", |
| 324 | + "version": "3.12.6" |
| 325 | + } |
| 326 | + }, |
| 327 | + "nbformat": 4, |
| 328 | + "nbformat_minor": 5 |
| 329 | +} |
0 commit comments