{ "cells": [ { "cell_type": "raw", "metadata": {}, "source": [ "Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2017 L.A. Barba, N.C. Clementi" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Interacting with Python\n", "\n", "This is the first lesson in our series _\"Engineering Computations\"_, a set of learning modules for university students in science and engineering. The modules use Python, assuming no prior programming experience at the beginning of the series: this first module is titled **\"Get Data Off the Ground with Python\"** and is made up of five lessons, leading to a case study of linear regression with real data.\n", "Our first goal will be to get you interacting with Python and handling data in Python.\n", "But let's also learn a little bit of background." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What is Python?\n", "\n", "Python was born in the late 1980s and released publicly in February 1991. Its creator, [Guido van Rossum](https://en.wikipedia.org/wiki/Guido_van_Rossum), named it after the British comedy \"Monty Python's Flying Circus.\" His goal was to create \"an easy and intuitive language just as powerful as major competitors,\" producing computer code \"that is as understandable as plain English.\"\n", "\n", "We say that Python 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_.\n", "\n", "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.\n", "A neat ability of Python is to be used _interactively_. [Fernando Perez](https://en.wikipedia.org/wiki/Fernando_Pérez_(software_developer)) famously created **IPython** as a side-project during his PhD. The \"I\" in IPython stands for interactive: a style of computing that is very powerful for developing ideas and solutions incrementally, thinking with the computer as a kind of collaborator. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Why Python?\n", "\n", "\n", "_Because it's fun!_ With Python, the more you learn, the more you _want_ to learn.\n", "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. \n", "_And it's free!_\n", "\n", "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 other languages. \n", "This is important to always bring up whenever someone complains that \"Python is slow.\"\n", "Your time is more valuable than a machine's!\n", "(See the Recommended Readings section at the end of this lesson.)\n", "And if we really need to speed up our program, we can re-write the slow parts in a compiled language afterwards.\n", "Because Python plays well with other languages :–)\n", "\n", "The top technology companies use Python: Google, Facebook, Dropbox, Wikipedia, Yahoo!, YouTube, and more. Python took the No. 1 spot in the list of [The 2017 Top Programming Languages](http://spectrum.ieee.org/computing/software/the-2017-top-programming-languages) by _IEEE Spectrum_, and continues on the top spot into [the 2023 list](https://spectrum.ieee.org/top-programming-languages-2023). ([IEEE](http://www.ieee.org/about/index.html) is the world's largest technical professional society). Another list, [PYPL](https://pypl.github.io/PYPL.html) (PopularitY of Programming Language) shows it consistently at the top, too." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> _\"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](https://youtu.be/rkx5_MRAV3A)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What's new in 2023?\n", "\n", "Python is not only the most popular programming language, it is also the major language for artificial intelligence (AI), and machine learning (ML) in particular. \n", "\n", "These lessons were originally written in 2017. Six years later, in 2023, we have a surge of AI applications that bode drastic changes across society. AI tools can even help you write Python code and solve problems much more quickly. More than ever, it will serve every student well to know Python, and these lessons can get you there." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Let's get started\n", "\n", "You could follow this first lesson using IPython. If you have it installed in the computer you're using, you enter the program by typing `ipython` on the command-line interface (the **Terminal** app on Mac OSX, and on Windows the **PowerShell** or a similar app). \n", "A free service to try IPython online, right from your browser, is [Python Anywhere](https://www.pythonanywhere.com/try-ipython/). You can execute all the examples of this lesson in IPython using this service. \n", "\n", "You can also use Jupyter: an environment that combines programming with other content, like text and images, to form a \"computational narrative.\" This very lesson is written in Jupyter. \n", "The next lesson in this module will go into details about what is Jupyter and how to work with Jupyter. \n", "\n", "For this lesson, we will assume you have been guided to open a blank Jupyter notebook, or are working interactively with this lesson. \n", "On a blank Jupyter notebook (or IPython), you should have in front of you the input line counter:\n", "\n", "`In[1]:`\n", "\n", "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 in IPython, or code cells in Jupyter." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### _Note:_\n", "\n", "We wrote these lessons to use in a face-to-face course led in a computer lab, with any software installed ahead of time, or with access to a cloud server for Jupyter. For this reason, we don't discuss installation of the needed software. \n", "But if you don't have Python and Jupyter installed in your machine, you can interact with these lessons online via the free Binder service. \n", "\n", "[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/engineersCode/EngComp1_offtheground/master)\n", "#### _Click the button to launch a session!_" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Your first program\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello world!!\n" ] } ], "source": [ "print(\"Hello world!!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### _Key concept: function_\n", "\n", "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.\n", "\n", "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 friends." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Python as a calculator\n", "\n", "Try any arithmetic operation in IPython or a Jupyter code cell. 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:\n", "\n", "```python\n", "+ - * / ** % //\n", "```\n", "\n", "The `%` symbol is the _modulo_ operator (divide and return the remainder), and the double-slash is _floor division_." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 + 2" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4.9" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1.25 + 3.65" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "5 - 3" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 * 4" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3.5" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "7 / 2" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2**3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's see an interesting case:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4.5" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "9**1/2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Discuss with your neighbor:\n", "_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?\n", "\n", "Compare with this:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3.0" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "9**(1/2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Yes! The order of operations matters! \n", "\n", "If you don't remember what we are talking about, review the [Arithmetics/Order of operations](https://en.wikibooks.org/wiki/Arithmetic/Order_of_Operations). A frequent situation that exposes this is the following:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4.5" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3 + 3 / 2" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3.0" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(3 + 3) / 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### _Exercises:_\n", "Use Python (as a calculator) to solve the following two problems:\n", "\n", "1. 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?\n", "\n", " For the value of $\\pi$ use 3.14159 (for now). Compare your answer with the solution up to 4 decimal numbers.\n", "\n", " Hint: 523.5983 is wrong and 615.9184 is also wrong.\n", " \n", "2. 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.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To reveal the answers, highlight the following line of text using the mouse:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Answer exercise 1: 153.9796 Answer exercise 2: 945.45 " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Variables and their type\n", "\n", "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. \n", "\n", "The first thing to get used to is that the equal sign in a variable assignment has a different meaning than it has in Algebra! Think of it as an arrow pointing from `name` to `value`.\n", "\n", "\n", " \n", "\n", "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:\n", "\n", "```\n", " x\n", " x1\n", " X_2\n", " name_3\n", " NameLastname\n", "```\n", "Keep in mind, there are reserved words that you can't use; they are the special Python [keywords](https://docs.python.org/3/reference/lexical_analysis.html#keywords).\n", " \n", "OK. Let's assign some values to variables and do some operations with them: " ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": true, "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "x = 3 " ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": true, "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "y = 4.5" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### _Exercise:_\n", "Print the values of the variables `x` and `y`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's do some arithmetic operations with our new variables:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7.5" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x + y" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2**x" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.5" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y - 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And now, let's check the values of `x` and `y`. Are they still the same as they were when you assigned them?\n" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n" ] } ], "source": [ "print(x)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4.5\n" ] } ], "source": [ "print(y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### String variables\n", "\n", "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`.\n" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": true, "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "z = 'this is a string'" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": true, "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "w = '1'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " What if you try to \"add\" two strings?" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'this is a string1'" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "z + w" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The operation above is called _concatenation_: chaining two strings together into one. Insteresting, eh? But look at this: " ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "unsupported operand type(s) for +: 'int' and 'str'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mx\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mw\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'" ] } ], "source": [ "x + w" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "_Error!_ Why? Let's inspect what Python has to say and explore what is happening. \n", "\n", "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\":\n", "\n", "> \"If it looks like a duck, and quacks like a duck, then it's probably a duck.\"\n", "\n", "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).\n", "\n", "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()`." ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(x)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(w)" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "float" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### More assignments\n", "\n", "What if you want to assign to a new variable the result of an operation that involves other variables? Well, you totally can!" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": true, "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "sum_xy = x + y\n", "diff_xy = x - y" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The sum of x and y is: 7.5\n", "The difference between x and y is: -1.5\n" ] } ], "source": [ "print('The sum of x and y is:', sum_xy)\n", "print('The difference between x and y is:', diff_xy)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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:" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "float" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(sum_xy)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "float" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(diff_xy)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Discuss with your neighbor:\n", "Can you summarize what we did above?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Special variables\n", "\n", "Python has special variables that are built into the language. These are: \n", "`True`, `False`, `None` and `NotImplemented`. \n", "For now, we will look at just the first three of these.\n", "\n", "**Boolean variables** are used to represent truth values, and they can take one of two possible values: `True` and `False`.\n", "_Logical expressions_ return a boolean. Here is the simplest logical expression, using the keyword `not`:\n", "\n", "```Python\n", " not True\n", "```\n", "\n", "It returns… you guessed it… `False`.\n", "\n", "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.\n" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool(0)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool('Do we need oxygen?')" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool('We do not need oxygen')" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true, "jupyter": { "outputs_hidden": true } }, "source": [ "**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. \n", "\n", "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:" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "collapsed": true, "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "a = None\n", "\n", "b = 3" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "unsupported operand type(s) for +: 'NoneType' and 'int'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0ma\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'NoneType' and 'int'" ] } ], "source": [ "a + b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Logical and comparison operators\n", "\n", "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!" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "collapsed": true, "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "x = 3\n", "y = 5" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x > y" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can assign the truth value of a comparison operation to a new variable name:" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "collapsed": true, "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "z = x > y" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "z" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "bool" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(z)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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.\n", "\n", "Let's do some examples:" ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "collapsed": true, "jupyter": { "outputs_hidden": true } }, "outputs": [], "source": [ "a = 5\n", "b = 3\n", "c = 10" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a > b and b > c" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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`. \n", "\n", "If we try the `or` operation using the same operands we should get a `True`. " ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a > b or b > c" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And the negation of the second operand results in …" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "not b > c" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What if we negate the second operand in the `and` operation above?\n", "\n", "##### _Note:_ \n", "\n", "Be careful with the order of logical operations. The order of precedence in logic is:\n", "\n", "1. Negation\n", "2. And\n", "3. Or\n", "\n", "If you don't rememeber this, make sure to use parentheses to indicate the order you want. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### _Exercise:_\n", "\n", "What is happening in the case below? Play around with logical operators and try some examples. " ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a > b and not b > c" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What we've learned\n", "\n", "* Using the `print()` function. The concept of _function_.\n", "* Using Python as a calculator.\n", "* Concepts of variable, type, assignment.\n", "* Special variables: `True`, `False`, `None`.\n", "* Supported operations, logical operations. \n", "* Reading error messages." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## References\n", "\n", "Throughout this course module, we will be drawing from the following references:\n", "\n", "1. _Effective Computation in Physics: Field Guide to Research with Python_ (2015). Anthony Scopatz & Kathryn D. Huff. O'Reilly Media, Inc.\n", "2. _Python for Everybody: Exploring Data Using Python 3_ (2016). Charles R. Severance. [PDF available](http://do1.dr-chuck.com/pythonlearn/EN_us/pythonlearn.pdf)\n", "3. _Think Python: How to Think Like a Computer Scientist_ (2012). Allen Downey. Green Tea Press. [PDF available](http://greenteapress.com/thinkpython/thinkpython.pdf)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Recommended Readings\n", "\n", "- [\"Yes, Python is Slow, and I Don’t Care\"](https://medium.com/pyslackers/yes-python-is-slow-and-i-dont-care-13763980b5a1) by Nick Humrich, on Medium. (Skip the part on microservices, which is a bit specialized, and continue after the photo of moving car lights.)\n", "- [\"Why I Push for Python\"](http://lorenabarba.com/blog/why-i-push-for-python/), by Prof. Lorena A. Barba (2014). This blog post got a bit of interest over at [Hacker News](https://news.ycombinator.com/item?id=7760870)." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Execute this cell to load the notebook's style sheet, then ignore it\n", "from IPython.core.display import HTML\n", "HTML(open('../../../styles/custom.css', \"r\").read())" ] } ], "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.11.6" }, "widgets": { "state": {}, "version": "1.1.2" } }, "nbformat": 4, "nbformat_minor": 4 }