summaryrefslogtreecommitdiff
path: root/tutorials/module_1/basics_of_python.ipynb
blob: fc98569798116824035c61e3239e172bfabcdeb3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a5c32509-d4c7-4fd5-92cf-1a923b78f443",
   "metadata": {},
   "source": [
    "# Basics of Python\n",
    "\n",
    "This page contains important fundamental concepts used in Python such as syntax, operators, order or precedence and more.\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "01d694d9-2a73-4ba0-be56-dfa9b819a11a",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "## Syntax\n",
    "\n",
    "### Indentations and blocks\n",
    "In python *indentations* or the space at the start of each line, signifies a block of code. This becomes important when we start working with function and loops. We will talk more about this in the controls structures tutorial. \n",
    "\n",
    "### Comments\n",
    "Comments can be added to your code using the hash operator (#). Any text behind the comment operator till the end of the line will be rendered as a comment.\n",
    "If you have an entire block of text or code that needs to be commented out, the triple quotation marks (\"\"\") can be used. Once used all the code after it will be considered a comment until the comment is ended with the triple quotation marks.\n",
    "\n",
    " ---"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "e0c46483-6263-4a7c-b1cc-bc932d3a1393",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "## Operators\n",
    "In python, operators are special symbols or keywords that perform operations on values or variables. This section covers some of the most common operator that you will see in this course.\n",
    "\n",
    "### Arithmetic operators\n",
    "| Operator | Name           |\n",
    "| ---      | ---            |\n",
    "| +        | Addition       |\n",
    "| -        | Subtraction    |\n",
    "| *        | Multiplication |\n",
    "| /        | Division       |\n",
    "| %        | Modulus        |\n",
    "| **       | Exponentiation |\n",
    "| //       | Floor division |\n",
    "\n",
    "### Comparison operators\n",
    "Used in conditional statements such as `if` statements or `while` loops. Note that in the computer world a double equal sign (`==`) means *is equal to*, where as the single equal sign assigns the variable or defines the variable to be something. \n",
    "\n",
    "| Operator | Name                     |\n",
    "| ---      | ---                      |\n",
    "| ==       | Equal                    |\n",
    "| !=       | Not equal                |\n",
    "| >        | Greater than             |\n",
    "| <        | Less than                |\n",
    "| >=       | Greater than or equal to |\n",
    "| <=       | Less than or equal to    |\n",
    "\n",
    "### Logical operators\n",
    "| Operator | Descrription                                           |\n",
    "| ---      | ---                                                    |\n",
    "| and      | Returns True if both statemetns are true               |\n",
    "| or       | Returns True if one of the statements is true          |\n",
    "| not      | Reerse the result, returns False if the result is true |\n",
    "\n",
    "### Identity operators\n",
    "| Operator | Description                                            |\n",
    "| ---      | ---                                                    |\n",
    "| is       | Returns True if both variables are the same object     |\n",
    "| is not   | Returns True if both variables are not the same object |\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f22ddf1-592a-4a43-897c-e3addc57df24",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "## Order of Operation\n",
    "Similarly to the order or precedence in mathematics, different computer languages have their own set of rules. Here is a comprehensive table of the order of operation that python follows.\n",
    "\n",
    "| Operator                                                | Description                                           |\n",
    "| ------------------------------------------------------- | ----------------------------------------------------- |\n",
    "| `()`                                                    | Parentheses                                           |\n",
    "| `**`                                                    | Exponentiation                                        |\n",
    "| `+x` `-x` `~x`                                          | Unary plus, unary minus, and bitwise NOT              |\n",
    "| `*` `/` `//` `%`                                        | Multiplication, Division, floor division, and modulus |\n",
    "| `+` `-`                                                 | Addition and subtraction                              |\n",
    "| `<<` `>>`                                               | Bitwise left and right shifts                         |\n",
    "| &                                                       | Bitwise AND                                           |\n",
    "| ^                                                       | Bitwise XOR                                           |\n",
    "| \\|                                                      | Bitwise OR                                            |\n",
    "| `==` `!=` `>` `>=` `<` `<=` `is` `is not` `in` `not in` | Comparision, identity and membership operators        |\n",
    "| `not`                                                   | logical NOT                                           |\n",
    "| `and`                                                   | AND                                                   |\n",
    "| `or`                                                    | OR                                                    |\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c79d7d3-5f06-4206-9f90-46a02f9b3ffb",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "## Data types\n",
    "Data types are different ways a computer stores data. Other data types use fewer bits than others allowing you to better utilize your computer memory. This is important for engineers because\n",
    "The most common data types that an engineer encounters in python are numeric types.\n",
    "- `int` - integer\n",
    "- `float` - a decimal number\n",
    "- `complex` - imaginary number\n",
    "\n",
    "The comprehensive table below show all built-in data types available in python.\n",
    "\n",
    "| Category | Data Type                    |\n",
    "| -------- | ---------------------------- |\n",
    "| Text     | int, float, complex          |\n",
    "| Sequance | list, tuple, range           |\n",
    "| Mapping  | dict                         |\n",
    "| Set      | set, frozenset               |\n",
    "| Boolean  | bytes, bytearray, memoryview |\n",
    "| Binary   | bytes, bytearray, memoryview |\n",
    "| None     | NoneType                     |\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6edf45e8-504c-415e-9b74-852332167097",
   "metadata": {},
   "source": [
    "## Variables\n",
    "\n",
    "A **variable** in Python is a name that stores a value, allowing you to use and manipulate data efficiently.\n",
    "\n",
    "#### Declaring and Assigning Variables\n",
    "\n",
    "It is common in low-level computer languages to declare the datatype if the variable. In python, the datatype is set whilst you assign it. We assign values to variables using a single `=`. \n",
    "\n",
    "```python"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "125e385b-27dd-4139-8904-10996b536331",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1098.42\n"
     ]
    }
   ],
   "source": [
    "x = 33          # Integer\n",
    "y = 3.14        # Float\n",
    "name = \"Joe\"    # String\n",
    "is_valid = True # Boolean\n",
    "\n",
    "print(x**2+3*y)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98b37bca-8821-4866-8973-80a3315aba0b",
   "metadata": {},
   "source": [
    "Change the x and y values above, re-run the cell to see what happens.\n",
    "\n",
    "You can assign multiple variables at once or on the same line."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "6d9e59c3-1f38-444a-b09b-6914dba7233a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2 7.3 5.3 2.71828 2.71828 2.71828\n"
     ]
    }
   ],
   "source": [
    "a, b, c = 2, 7.3, 5.3\n",
    "\n",
    "x = y = z = 2.71828\n",
    "\n",
    "print(a,b,c,x,y,z)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "691c0a0a-6143-4ba5-b92a-769979b7d695",
   "metadata": {},
   "source": [
    "##### Rules\n",
    "\n",
    "- Must start with a letter or `_`\n",
    "- Cannot start with a number\n",
    "- Can only contain letters, numbers, and `_`\n",
    "- Case-sensitive (`Name` and `name` are different)\n",
    "\n",
    "#### Updating Variables\n",
    "\n",
    "You can change a variable’s value at any time.\n",
    "\n",
    "```python\n",
    "x = 5\n",
    "x = x + 10  # Now x is 15\n",
    "```\n",
    "\n",
    "Or shorthand:\n",
    "\n",
    "```python\n",
    "x += 10  # Same as x = x + 10\n",
    "```\n",
    "\n",
    "#### Variable Types & Type Checking\n",
    "\n",
    "Use `type()` to check a variable’s type."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "a7e71be9-dd9a-42c9-84e2-cb5f8f8939b1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Variable x is type: <class 'int'>\n",
      " Variable y is type: <class 'str'>\n"
     ]
    }
   ],
   "source": [
    "x = 10\n",
    "print(f' Variable x is type: {type(x)}')\n",
    "\n",
    "y = \"Hello\"\n",
    "print(f' Variable y is type: {type(y)}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fcdca3e3-4386-4515-abbe-13242b55c2d7",
   "metadata": {},
   "source": [
    "# Exercise\n",
    "\n",
    "You're analyzing a cylindrical steel rod under axial load for a design. The goal is to calculate the stress in the rod and determine if it is within safe limits.\n",
    "\n",
    "Given an applied force of 15,000 N on a rod with the diameter 22 mm and a yield strength of steel 250 MPa.\n",
    "\n",
    "Hint:\n",
    "\n",
    "$Stress=\\frac{Force}{Area}$ , $Area=\\frac{π d^2}{4}$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "cdcc3fde-b63e-4443-a8a1-b59396d3560e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Stress in rod: 39.5 MPa\n",
      "The design is SAFE under the given load.\n"
     ]
    }
   ],
   "source": [
    "# Given\n",
    "force_N = 15000\n",
    "D_mm = 22\n",
    "sigma_MPa = 250\n",
    "\n",
    "# Equations\n",
    "area = 3.14* D_mm**2 / 4\n",
    "stress = force_N / area\n",
    "\n",
    "# Print output\n",
    "print(f\"Stress in rod: {stress:.1f} MPa\")\n",
    "\n",
    "# Check safety\n",
    "if stress < sigma_MPa:\n",
    "    print(\"The design is SAFE under the given load.\")\n",
    "else:\n",
    "    print(\"The design FAILED. Consider redesigning.\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.13.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}