This is the first lesson in our course "Engineering Computations", a one-semester course for second-year university students. The course uses Python, and assumes no prior programming experience.
14 | Our first step will be to get you interacting with Python.
15 | But let's also learn some background.
Python is now 26 years old. Its creator, Guido van Rossum, named it after the British comedy "Monty Python's Flying Circus." His goals for the language were that it be an "an easy and intuitive language just as powerful as major competitors," producing computer code "that is as understandable as plain English."
25 |
It is a general-purpose language, which means that you can use it for anything: organizing data, scraping the web, creating websites, analyzing sounds, creating games, and of course engineering computations.
26 |
Python is an interpreted language. This means that you can write Python commands and the computer can execute those instructions directly. Other programming languages—like C, C++ and Fortran—require a previous compilation step: translating the commands into machine language.
27 | A neat ability of Python is to be used interactively. Fernando Perez) famously created IPython as a side-project during his PhD. We're going to use IPython (the I stands for "interactive") in this lesson.
Because it's fun! With Python, the more you learn, the more you want to learn.
37 | You can find lots of resources online and, since Python is an open-source project, you'll also find a friendly community of people sharing their knowledge.
38 |
Python is known as a high-productivity language. As a programmer, you'll need less time to develop a solution with Python than with most languages.
39 | This is important to always bring up whenever someone complains that "Python is slow."
40 | Your time is more valuable than a machine's!
41 | (See the Recommended Readings section at the end.)
42 | And if we really need to speed up our program, we can re-write the slow parts in a compiled language afterwards.
43 | Because Python plays well with other languages :–)
44 |
The top technology companies use Python: Google, Facebook, Dropbox, Wikipedia, Yahoo!, YouTube… And this year, Python took the No. 1 spot in the interactive list of The 2017 Top Programming Languages, by IEEE Spectrum (IEEE is the world's largest technical professional society).
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
Python is a versatile language, you can analyze data, build websites (e.g., Instagram, Mozilla, Pinterest), make art or music, etc. Because it is a versatile language, employers love Python: if you know Python they will want to hire you. —Jessica McKellar, ex Director of the Python Software Foundation, in a 2014 tutorial.¶
In this first lesson, we will be using IPython: a tool for working with Python interactively. If you have it installed in the computer you're using for this lesson, you enter the program by typing
62 |
ipython
63 |
on the command-line interface (the Terminal app on Mac OSX, and on Windows possibly the PowerShell or git bash). You will get a few lines of text about your IPython version and how to get help, and a blinking cursor next to the input line counter:
64 |
In[1]:
65 |
That input line is ready to receive any Python code to be executed interactively. The output of the code will be shown to you next to Out[1], and so on for successive input/output lines.
Our plan for this course is to work in a computer lab, where everyone will have a computer with everything installed ahead of time. For this reason, we won't discuss installation right now. Later on, when you're eager to work on your personal computer, we'll help you install everything you need. It's all free!
In every programming class ever, your first program consists of printing a "Hello" message. In Python, you use the print() function, with your message inside quotation marks.
76 |
77 |
78 |
79 |
80 |
81 |
82 |
In [1]:
83 |
84 |
85 |
print("Hello world!!")
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
Hello world!!
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
Easy peasy!! You just wrote your first program and you learned how to use the print() function. Yes, print() is a function: we pass the argument we want the function to act on, inside the parentheses. In the case above, we passed a string, which is a series of characters between quotation marks. Don't worry, we will come back to what strings are later on in this lesson.
A function is a compact collection of code that executes some action on its arguments. Every Python function has a name, used to call it, and takes its arguments inside round brackets. Some arguments may be optional (which means they have a default value defined inside the function), others are required. For example, the print() function has one required argument: the string of characters it should print out for you.
125 |
Python comes with many built-in functions, but you can also build your own. Chunking blocks of code into functions is one of the best strategies to deal with complex programs. It makes you more efficient, because you can reuse the code that you wrote into a function. Modularity and reuse are every programmer's friend.
Try any arithmetic operation in IPython. The symbols are what you would expect, except for the "raise-to-the-power-of" operator, which you obtain with two asterisks: **. Try all of these:
135 |
+-*/**%//
136 |
137 |
The % symbol is the modulo operator (divide and return remainder), and the double-slash is floor division.
What happened? Isn't $9^{1/2} = 3$? (Raising to the power $1/2$ is the same as taking the square root.) Did Python get this wrong?
387 |
Compare with this:
388 |
389 |
390 |
391 |
392 |
393 |
394 |
In [9]:
395 |
396 |
397 |
9**(1/2)
398 |
399 |
400 |
401 |
402 |
403 |
404 |
405 |
406 |
407 |
408 |
409 |
410 |
Out[9]:
411 |
412 |
413 |
414 |
415 |
416 |
3.0
417 |
418 |
419 |
420 |
421 |
422 |
423 |
424 |
425 |
426 |
427 |
428 |
429 |
Yes! The order of operations matters!
430 |
If you don't remember what we are talking about, review the Arithmetics/Order of operations. A frequent situation that exposes this is the following:
431 |
432 |
433 |
434 |
435 |
436 |
437 |
In [10]:
438 |
439 |
440 |
3+3/2
441 |
442 |
443 |
444 |
445 |
446 |
447 |
448 |
449 |
450 |
451 |
452 |
453 |
Out[10]:
454 |
455 |
456 |
457 |
458 |
459 |
4.5
460 |
461 |
462 |
463 |
464 |
465 |
466 |
467 |
468 |
469 |
470 |
In [11]:
471 |
472 |
473 |
(3+3)/2
474 |
475 |
476 |
477 |
478 |
479 |
480 |
481 |
482 |
483 |
484 |
485 |
486 |
Out[11]:
487 |
488 |
489 |
490 |
491 |
492 |
3.0
493 |
494 |
495 |
496 |
497 |
498 |
499 |
500 |
501 |
502 |
503 |
504 |
505 |
In the first case, we are adding $3$ plus the number resulting of the operation $3/2$. If we want the division to apply to the result of $3+3$, we need the parentheses.
Use IPython (as a calculator) to solve the following two problems:
515 |
516 |
The volume of a sphere with radius $r$ is $\frac{4}{3}\pi r^3$. What is the volume of a sphere with diameter 6.65 cm?
517 |
For the value of $\pi$ use 3.14159 (for now). Compare your answer with the solution up to 4 decimal numbers.
518 |
Hint: 523.5983 is wrong and 615.9184 is also wrong.
519 |
520 |
Suppose the cover price of a book is $\$ 24.95$, but bookstores get a $40\%$ discount. Shipping costs $\$3$ for the first copy and $75$ cents for each additional copy. What is the total wholesale cost for $60$ copies? Compare your answer with the solution up to 2 decimal numbers.
521 |
522 |
523 |
524 |
525 |
526 |
527 |
528 |
529 |
530 |
531 |
To reveal the answers, highlight the following line of text using the mouse:
Variables consist of two parts: a name and a value. When we want to give a variable its name and value, we use the equal sign: name = value. This is called an assignment. The name of the variable goes on the left and the value on the right.
550 |
The first thing to get used to is that the equal sign in an assignment has a different meaning than it has in Algebra! Think of it as an arrow pointing from name to value.
551 |
552 |
We have many possibilities for variable names: they can be made up of upper and lowercase letters, underscores and digits… although digits cannot go on the front of the name. For example, valid variable names are:
In addition to name and value, Python variables have a type: the type of the value it refers to. For example, an integer value has type int, and a real number has type float. A string is a variable consisting of a sequence of characters marked by two quotes, and it has type str.
784 |
785 |
786 |
787 |
788 |
789 |
790 |
In [19]:
791 |
792 |
793 |
z='this is a string'
794 |
795 |
796 |
797 |
798 |
799 |
800 |
801 |
802 |
803 |
In [20]:
804 |
805 |
806 |
w='1'
807 |
808 |
809 |
810 |
811 |
812 |
813 |
814 |
815 |
816 |
817 |
818 |
What if you try to "add" two strings?
819 |
820 |
821 |
822 |
823 |
824 |
825 |
In [21]:
826 |
827 |
828 |
z+w
829 |
830 |
831 |
832 |
833 |
834 |
835 |
836 |
837 |
838 |
839 |
840 |
841 |
Out[21]:
842 |
843 |
844 |
845 |
846 |
847 |
'this is a string1'
848 |
849 |
850 |
851 |
852 |
853 |
854 |
855 |
856 |
857 |
858 |
859 |
860 |
The operation above is called concatenation: chaining two strings together into one. Insteresting, eh? But look at this:
861 |
862 |
863 |
864 |
865 |
866 |
867 |
In [22]:
868 |
869 |
870 |
x+w
871 |
872 |
873 |
874 |
875 |
876 |
877 |
878 |
879 |
880 |
881 |
882 |
883 |
884 |
885 |
886 |
887 |
888 | ---------------------------------------------------------------------------
889 | TypeError Traceback (most recent call last)
890 | <ipython-input-22-bc79f95cdaf2> in <module>()
891 | ----> 1x + w
892 |
893 | TypeError: unsupported operand type(s) for +: 'int' and 'str'
894 |
895 |
896 |
897 |
898 |
899 |
900 |
901 |
902 |
903 |
904 |
905 |
Error! Why? Let's inspect what Python has to say and explore what is happening.
906 |
Python is a dynamic language, which means that you don't need to specify a type to invoke an existing object. The humorous nickname for this is "duck typing":
907 |
"If it looks like a duck, and quacks like a duck, then it's probably a duck."¶
In other words, a variable has a type, but we don't need to specify it. It will just behave like it's supposed to when we operate with it (it'll quack and walk like nature intended it to).
908 |
But sometimes you need to make sure you know the type of a variable. Thankfully, Python offers a function to find out the type of a variable: type().
What if you want to assign to a new variable the result of an operation that involves other variables? Well, you totally can!
1017 |
1018 |
1019 |
1020 |
1021 |
1022 |
1023 |
In [26]:
1024 |
1025 |
1026 |
sum_xy=x+y
1027 | diff_xy=x-y
1028 |
1029 |
1030 |
1031 |
1032 |
1033 |
1034 |
1035 |
1036 |
1037 |
In [27]:
1038 |
1039 |
1040 |
print('The sum of x and y is:',sum_xy)
1041 | print('The difference between x and y is:',diff_xy)
1042 |
1043 |
1044 |
1045 |
1046 |
1047 |
1048 |
1049 |
1050 |
1051 |
1052 |
1053 |
1054 |
1055 |
1056 |
1057 |
1058 |
The sum of x and y is: 7.5
1059 | The difference between x and y is: -1.5
1060 |
1061 |
1062 |
1063 |
1064 |
1065 |
1066 |
1067 |
1068 |
1069 |
1070 |
1071 |
1072 |
Notice what we did above: we used the print() function with a string message, followed by a variable, and Python printed a useful combination of the message and the variable value. This is a pro tip! You want to print for humans. Let's now check the type of the new variables we just created above:
Python has special variables that are built into the language. These are:
1157 | True, False, None and NotImplemented.
1158 | For now, we will look at just the first three of these.
1159 |
Boolean variables are used to represent truth values, and they can take one of two possible values: True and False.
1160 | Logical expressions return a boolean. Here is the simplest logical expression, using the keyword not:
1161 |
notTrue
1162 |
1163 |
It returns… you guessed it… False.
1164 |
The Python function bool() returns a truth value assigned to any argument. Any number other than zero has a truth value of True, as well as any nonempty string or list. The number zero and any empty string or list will have a truth value of False. Explore the bool() function with various arguments.
1165 |
1166 |
1167 |
1168 |
1169 |
1170 |
1171 |
In [30]:
1172 |
1173 |
1174 |
bool(0)
1175 |
1176 |
1177 |
1178 |
1179 |
1180 |
1181 |
1182 |
1183 |
1184 |
1185 |
1186 |
1187 |
Out[30]:
1188 |
1189 |
1190 |
1191 |
1192 |
1193 |
False
1194 |
1195 |
1196 |
1197 |
1198 |
1199 |
1200 |
1201 |
1202 |
1203 |
1204 |
In [31]:
1205 |
1206 |
1207 |
bool('Do we need oxygen?')
1208 |
1209 |
1210 |
1211 |
1212 |
1213 |
1214 |
1215 |
1216 |
1217 |
1218 |
1219 |
1220 |
Out[31]:
1221 |
1222 |
1223 |
1224 |
1225 |
1226 |
True
1227 |
1228 |
1229 |
1230 |
1231 |
1232 |
1233 |
1234 |
1235 |
1236 |
1237 |
In [32]:
1238 |
1239 |
1240 |
bool('We do not need oxygen')
1241 |
1242 |
1243 |
1244 |
1245 |
1246 |
1247 |
1248 |
1249 |
1250 |
1251 |
1252 |
1253 |
Out[32]:
1254 |
1255 |
1256 |
1257 |
1258 |
1259 |
True
1260 |
1261 |
1262 |
1263 |
1264 |
1265 |
1266 |
1267 |
1268 |
1269 |
1270 |
1271 |
1272 |
None is not Zero: None is a special variable indicating that no value was assigned or that a behavior is undefined. It is different than the value zero, an empty string, or some other nil value.
1273 |
You can check that it is not zero by trying to add it to a number. Let's see what happens when we try that:
1274 |
1275 |
1276 |
1277 |
1278 |
1279 |
1280 |
In [33]:
1281 |
1282 |
1283 |
a=None
1284 |
1285 | b=3
1286 |
1287 |
1288 |
1289 |
1290 |
1291 |
1292 |
1293 |
1294 |
1295 |
In [34]:
1296 |
1297 |
1298 |
a+b
1299 |
1300 |
1301 |
1302 |
1303 |
1304 |
1305 |
1306 |
1307 |
1308 |
1309 |
1310 |
1311 |
1312 |
1313 |
1314 |
1315 |
1316 | ---------------------------------------------------------------------------
1317 | TypeError Traceback (most recent call last)
1318 | <ipython-input-34-f96fb8f649b6> in <module>()
1319 | ----> 1a + b
1320 |
1321 | TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
The Python comparison operators are: <, <=, >, >=, ==, !=. They compare two objects and return either True or False: smaller than, smaller or equal, greater than, greater or equal, equal, not equal. Try it!
1334 |
1335 |
1336 |
1337 |
1338 |
1339 |
1340 |
In [35]:
1341 |
1342 |
1343 |
x=3
1344 | y=5
1345 |
1346 |
1347 |
1348 |
1349 |
1350 |
1351 |
1352 |
1353 |
1354 |
In [36]:
1355 |
1356 |
1357 |
x>y
1358 |
1359 |
1360 |
1361 |
1362 |
1363 |
1364 |
1365 |
1366 |
1367 |
1368 |
1369 |
1370 |
Out[36]:
1371 |
1372 |
1373 |
1374 |
1375 |
1376 |
False
1377 |
1378 |
1379 |
1380 |
1381 |
1382 |
1383 |
1384 |
1385 |
1386 |
1387 |
1388 |
1389 |
We can assign the truth value of a comparison operation to a new variable name:
1390 |
1391 |
1392 |
1393 |
1394 |
1395 |
1396 |
In [37]:
1397 |
1398 |
1399 |
z=x>y
1400 |
1401 |
1402 |
1403 |
1404 |
1405 |
1406 |
1407 |
1408 |
1409 |
In [38]:
1410 |
1411 |
1412 |
z
1413 |
1414 |
1415 |
1416 |
1417 |
1418 |
1419 |
1420 |
1421 |
1422 |
1423 |
1424 |
1425 |
Out[38]:
1426 |
1427 |
1428 |
1429 |
1430 |
1431 |
False
1432 |
1433 |
1434 |
1435 |
1436 |
1437 |
1438 |
1439 |
1440 |
1441 |
1442 |
In [39]:
1443 |
1444 |
1445 |
type(z)
1446 |
1447 |
1448 |
1449 |
1450 |
1451 |
1452 |
1453 |
1454 |
1455 |
1456 |
1457 |
1458 |
Out[39]:
1459 |
1460 |
1461 |
1462 |
1463 |
1464 |
bool
1465 |
1466 |
1467 |
1468 |
1469 |
1470 |
1471 |
1472 |
1473 |
1474 |
1475 |
1476 |
1477 |
Logical operators are the following: and, or, and not. They work just like English (with the added bonus of being always consistent, not like English speakers!). A logical expression with and is True if both operands are true, and one with or is True when either operand is true. And the keyword not always negates the expression that follows.
1478 |
Let's do some examples:
1479 |
1480 |
1481 |
1482 |
1483 |
1484 |
1485 |
In [40]:
1486 |
1487 |
1488 |
a=5
1489 | b=3
1490 | c=10
1491 |
1492 |
1493 |
1494 |
1495 |
1496 |
1497 |
1498 |
1499 |
1500 |
In [41]:
1501 |
1502 |
1503 |
a>bandb>c
1504 |
1505 |
1506 |
1507 |
1508 |
1509 |
1510 |
1511 |
1512 |
1513 |
1514 |
1515 |
1516 |
Out[41]:
1517 |
1518 |
1519 |
1520 |
1521 |
1522 |
False
1523 |
1524 |
1525 |
1526 |
1527 |
1528 |
1529 |
1530 |
1531 |
1532 |
1533 |
1534 |
1535 |
Remember that the logical operator and is True only when both operands are True. In the case above the first operand is True but the second one is False.
1536 |
If we try the or operation using the same operands we should get a True.
1537 |
1538 |
1539 |
1540 |
1541 |
1542 |
1543 |
In [42]:
1544 |
1545 |
1546 |
a>borb>c
1547 |
1548 |
1549 |
1550 |
1551 |
1552 |
1553 |
1554 |
1555 |
1556 |
1557 |
1558 |
1559 |
Out[42]:
1560 |
1561 |
1562 |
1563 |
1564 |
1565 |
True
1566 |
1567 |
1568 |
1569 |
1570 |
1571 |
1572 |
1573 |
1574 |
1575 |
1576 |
1577 |
1578 |
And the negation of the second operand results in …
1579 |
1580 |
1581 |
1582 |
1583 |
1584 |
1585 |
In [43]:
1586 |
1587 |
1588 |
notb>c
1589 |
1590 |
1591 |
1592 |
1593 |
1594 |
1595 |
1596 |
1597 |
1598 |
1599 |
1600 |
1601 |
Out[43]:
1602 |
1603 |
1604 |
1605 |
1606 |
1607 |
True
1608 |
1609 |
1610 |
1611 |
1612 |
1613 |
1614 |
1615 |
1616 |
1617 |
1618 |
1619 |
1620 |
What if we negate the second operand in the and operation above?
"Yes, Python is Slow, and I Don’t Care" by Nick Humrich, on Hackernoon. (Skip the part on microservices, which is a bit specialized, and continue after the photo of moving car lights.)
# Execute this cell to load the notebook's style sheet, then ignore it
1722 | fromIPython.core.displayimportHTML
1723 | css_file='../../style/custom.css'
1724 | HTML(open(css_file,"r").read())
1725 |
This is the first lesson in our course "Engineering Computations", a one-semester course for second-year university students. The course uses Python, and assumes no prior programming experience.
26 |
27 | Our first step will be to get you interacting with Python.
28 |
29 | But let's also learn some background.
Python is now 26 years old. Its creator, Guido van Rossum, named it after the British comedy "Monty Python's Flying Circus." His goals for the language were that it be an "an easy and intuitive language just as powerful as major competitors," producing computer code "that is as understandable as plain English."
48 |
49 |
It is a general-purpose language, which means that you can use it for anything: organizing data, scraping the web, creating websites, analyzing sounds, creating games, and of course engineering computations.
50 |
51 |
Python is an interpreted language. This means that you can write Python commands and the computer can execute those instructions directly. Other programming languages—like C, C++ and Fortran—require a previous compilation step: translating the commands into machine language.
52 |
53 | A neat ability of Python is to be used interactively. Fernando Perez) famously created IPython as a side-project during his PhD. We're going to use IPython (the I stands for "interactive") in this lesson.
Because it's fun! With Python, the more you learn, the more you want to learn.
72 |
73 | You can find lots of resources online and, since Python is an open-source project, you'll also find a friendly community of people sharing their knowledge.
74 |
75 |
Python is known as a high-productivity language. As a programmer, you'll need less time to develop a solution with Python than with most languages.
76 |
77 | This is important to always bring up whenever someone complains that "Python is slow."
78 |
79 | Your time is more valuable than a machine's!
80 |
81 | (See the Recommended Readings section at the end.)
82 |
83 | And if we really need to speed up our program, we can re-write the slow parts in a compiled language afterwards.
84 |
85 | Because Python plays well with other languages :–)
86 |
87 |
The top technology companies use Python: Google, Facebook, Dropbox, Wikipedia, Yahoo!, YouTube… And this year, Python took the No. 1 spot in the interactive list of The 2017 Top Programming Languages, by IEEE Spectrum (IEEE is the world's largest technical professional society).
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
Python is a versatile language, you can analyze data, build websites (e.g., Instagram, Mozilla, Pinterest), make art or music, etc. Because it is a versatile language, employers love Python: if you know Python they will want to hire you. —Jessica McKellar, ex Director of the Python Software Foundation, in a 2014 tutorial.¶
In this first lesson, we will be using IPython: a tool for working with Python interactively. If you have it installed in the computer you're using for this lesson, you enter the program by typing
122 |
123 |
ipython
124 |
125 |
on the command-line interface (the Terminal app on Mac OSX, and on Windows possibly the PowerShell or git bash). You will get a few lines of text about your IPython version and how to get help, and a blinking cursor next to the input line counter:
126 |
127 |
In[1]:
128 |
129 |
That input line is ready to receive any Python code to be executed interactively. The output of the code will be shown to you next to Out[1], and so on for successive input/output lines.
Our plan for this course is to work in a computer lab, where everyone will have a computer with everything installed ahead of time. For this reason, we won't discuss installation right now. Later on, when you're eager to work on your personal computer, we'll help you install everything you need. It's all free!
In every programming class ever, your first program consists of printing a "Hello" message. In Python, you use the print() function, with your message inside quotation marks.
Easy peasy!! You just wrote your first program and you learned how to use the print() function. Yes, print() is a function: we pass the argument we want the function to act on, inside the parentheses. In the case above, we passed a string, which is a series of characters between quotation marks. Don't worry, we will come back to what strings are later on in this lesson.
A function is a compact collection of code that executes some action on its arguments. Every Python function has a name, used to call it, and takes its arguments inside round brackets. Some arguments may be optional (which means they have a default value defined inside the function), others are required. For example, the print() function has one required argument: the string of characters it should print out for you.
248 |
249 |
Python comes with many built-in functions, but you can also build your own. Chunking blocks of code into functions is one of the best strategies to deal with complex programs. It makes you more efficient, because you can reuse the code that you wrote into a function. Modularity and reuse are every programmer's friend.
Try any arithmetic operation in IPython. The symbols are what you would expect, except for the "raise-to-the-power-of" operator, which you obtain with two asterisks: **. Try all of these:
268 |
269 |
+-*/**%//
270 |
271 |
272 |
273 |
The % symbol is the modulo operator (divide and return remainder), and the double-slash is floor division.
In the first case, we are adding $3$ plus the number resulting of the operation $3/2$. If we want the division to apply to the result of $3+3$, we need the parentheses.
Use IPython (as a calculator) to solve the following two problems:
1028 |
1029 |
1030 |
1031 |
The volume of a sphere with radius $r$ is $\frac{4}{3}\pi r^3$. What is the volume of a sphere with diameter 6.65 cm?
1032 |
1033 |
For the value of $\pi$ use 3.14159 (for now). Compare your answer with the solution up to 4 decimal numbers.
1034 |
1035 |
Hint: 523.5983 is wrong and 615.9184 is also wrong.
1036 |
1037 |
1038 |
1039 |
Suppose the cover price of a book is $\$ 24.95$, but bookstores get a $40\%$ discount. Shipping costs $\$3$ for the first copy and $75$ cents for each additional copy. What is the total wholesale cost for $60$ copies? Compare your answer with the solution up to 2 decimal numbers.
1040 |
1041 |
1042 |
1043 |
1044 |
1045 |
1046 |
1047 |
1048 |
1049 |
1050 |
1051 |
1052 |
1053 |
1054 |
1055 |
1056 |
1057 |
1058 |
1059 |
1060 |
1061 |
To reveal the answers, highlight the following line of text using the mouse:
Variables consist of two parts: a name and a value. When we want to give a variable its name and value, we use the equal sign: name = value. This is called an assignment. The name of the variable goes on the left and the value on the right.
1098 |
1099 |
The first thing to get used to is that the equal sign in an assignment has a different meaning than it has in Algebra! Think of it as an arrow pointing from name to value.
1100 |
1101 |
1102 |
1103 |
We have many possibilities for variable names: they can be made up of upper and lowercase letters, underscores and digits… although digits cannot go on the front of the name. For example, valid variable names are:
In addition to name and value, Python variables have a type: the type of the value it refers to. For example, an integer value has type int, and a real number has type float. A string is a variable consisting of a sequence of characters marked by two quotes, and it has type str.
1774 |
1775 | ---------------------------------------------------------------------------
1776 |
1777 | TypeError Traceback (most recent call last)
1778 |
1779 | <ipython-input-22-bc79f95cdaf2> in <module>()
1780 |
1781 | ----> 1x + w
1782 |
1783 |
1784 |
1785 | TypeError: unsupported operand type(s) for +: 'int' and 'str'
1786 |
1787 |
1788 |
1789 |
1790 |
1791 |
1792 |
1793 |
1794 |
1795 |
1796 |
1797 |
1798 |
1799 |
1800 |
1801 |
1802 |
1803 |
1804 |
1805 |
1806 |
1807 |
1808 |
1809 |
Error! Why? Let's inspect what Python has to say and explore what is happening.
1810 |
1811 |
Python is a dynamic language, which means that you don't need to specify a type to invoke an existing object. The humorous nickname for this is "duck typing":
1812 |
1813 |
"If it looks like a duck, and quacks like a duck, then it's probably a duck."¶
In other words, a variable has a type, but we don't need to specify it. It will just behave like it's supposed to when we operate with it (it'll quack and walk like nature intended it to).
1814 |
1815 |
But sometimes you need to make sure you know the type of a variable. Thankfully, Python offers a function to find out the type of a variable: type().
The sum of x and y is: 7.5
2116 |
2117 | The difference between x and y is: -1.5
2118 |
2119 |
2120 |
2121 |
2122 |
2123 |
2124 |
2125 |
2126 |
2127 |
2128 |
2129 |
2130 |
2131 |
2132 |
2133 |
2134 |
2135 |
2136 |
2137 |
2138 |
2139 |
2140 |
2141 |
2142 |
2143 |
Notice what we did above: we used the print() function with a string message, followed by a variable, and Python printed a useful combination of the message and the variable value. This is a pro tip! You want to print for humans. Let's now check the type of the new variables we just created above:
Python has special variables that are built into the language. These are:
2312 |
2313 | True, False, None and NotImplemented.
2314 |
2315 | For now, we will look at just the first three of these.
2316 |
2317 |
Boolean variables are used to represent truth values, and they can take one of two possible values: True and False.
2318 |
2319 | Logical expressions return a boolean. Here is the simplest logical expression, using the keyword not:
2320 |
2321 |
notTrue
2322 |
2323 |
2324 |
2325 |
It returns… you guessed it… False.
2326 |
2327 |
The Python function bool() returns a truth value assigned to any argument. Any number other than zero has a truth value of True, as well as any nonempty string or list. The number zero and any empty string or list will have a truth value of False. Explore the bool() function with various arguments.
None is not Zero: None is a special variable indicating that no value was assigned or that a behavior is undefined. It is different than the value zero, an empty string, or some other nil value.
2544 |
2545 |
You can check that it is not zero by trying to add it to a number. Let's see what happens when we try that:
The Python comparison operators are: <, <=, >, >=, ==, !=. They compare two objects and return either True or False: smaller than, smaller or equal, greater than, greater or equal, equal, not equal. Try it!
Logical operators are the following: and, or, and not. They work just like English (with the added bonus of being always consistent, not like English speakers!). A logical expression with and is True if both operands are true, and one with or is True when either operand is true. And the keyword not always negates the expression that follows.
Remember that the logical operator and is True only when both operands are True. In the case above the first operand is True but the second one is False.
3070 |
3071 |
If we try the or operation using the same operands we should get a True.
"Yes, Python is Slow, and I Don’t Care" by Nick Humrich, on Hackernoon. (Skip the part on microservices, which is a bit specialized, and continue after the photo of moving car lights.)