Newer
Older
Gary Steele
committed
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**To do:**\n",
" Add YT clips as additional materials\n",
" Add np.array, list type\n",
" Add basic operations with np array / list \n",
" Difference between list and array \n",
" Add concatenate \n",
" Add append \n",
" Add movie with intro from teacher(s) and researchers on: why python?\n",
" "
]
},
Gary Steele
committed
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-e68e92ac1082dd04",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"# Python Basics\n",
"\n",
"In this course, you will work using a platform called \"Jupyter Notebooks\". Jupyter notebooks are a way to combine formatted text (like the text you are reading now), Python code (which you will use below), and the result of your code and calculations all in one place. Go through these notebooks and run the examples. Try to understand their functioning and, if necessary, add code (such as print statements or variable overviews) to make it clear for you. In addition, there are exercises and practice cells where you can program for yourself. Don't be afraid to start coding yourself, writing code and making mistakes is the best way to learn Python.\n",
"\n",
"In this lecture, you will learn the basic concepts of programming in Python. To get started, we will first explain the basic concepts of what python is and how it works. \n",
"\n",
"**Learning objectives for this notebook:**\n",
"\n",
"* Student is able to start the python interpreter and run code in a notebook\n",
"* Student can stop and start notebook kernels\n",
"* Student is able to create variables\n",
"* Student can use `%whos` to list the variables stored in the memory of the python kernel\n",
"* Student is able to determine the type of a variable \n",
"* Student is able to convert between different variable types (float, int, etc)\n",
"* Student is able to collect user input using the `input()` command\n",
"* Student is able to print variable values using the `print()` command\n",
"\n",
"## What is Python? And what are Jupyter Notebooks? \n",
"\n",
"Python is an (<a href=https://en.wikipedia.org/wiki/Interpreted_language>interpreted</a>) computer programming language. Using python, you can ask your computer to do specific things, like perform a calculation, draw a graph, load data from a file, or interact with the user. \n",
"\n",
"Every time you run python, either by running it on the command line, or by running it in a Jupyter notebook like you are now, a python **\"kernel\"** is created. This kernel is a copy of the python program (\"interpreter\") that runs continuously on your computer (until you stop it).\n",
"\n",
"Jupyter notebooks are a way to interact with the python kernel. Notebooks are divided up into \"cells\", which can be either a text cell (in a special text formatting language called <a href=https://en.wikipedia.org/wiki/Markdown>markdown</a>), like the one you are reading now. There are also code cell (containing your code), like the cell below it. \n",
Gary Steele
committed
"\n",
"The selected cell is surrounded by a box. If you type \"enter\" in a text cell you can start editing the cell. If you push \"Run\" above, or type \"Shift-Enter\", the code will be \"run\". If it is a code cell, it will run a command (see below). If it is a markdown cell, it will \"compile\" the markdown text language into formatted (HTML) text. \n",
"\n",
"You can give commands to this kernel by typing commands using the python language into the code cells of the notebook. Here, you can find an example of a code cell that contains a simple python command `print`, which prints a text string to the command line."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(\"Hello world\")"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-ee6ac0827c6a6783",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"To send this command to the python kernel, there are several options. First, select the cell (so that it is either blue or green), and then:\n",
"\n",
"1. Click on the **Run** button above in the toolbar. This will execute the cell and move you to the next cell.\n",
"2. Push **Shift-Enter**: this will do the same thing\n",
"3. Push **Control-Enter**: this will run the cell but leave it selected (useful if you want to re-run a cell a bunch of times)\n",
"\n",
"When you run the cell, the code will be sent to the python kernel, which will translate your python command into a binary language your computer CPU understands, send it to the CPU, and read back the answer. If the code you run produces an \"output\", meaning that the kernel will send something back to you, then the output that your code produces will be displayed below the code cell in the \"output\" section of the code cell. This is a scheme of what this process looks like \"behind the scenes\": \n",
"\n",
"<img width=60% src=\"resource/asnlib/public/Notebook_1_behind_the_scenes.png\"></img>\n",
"\n",
"After you have run the code cell, a number will appear beside your code cell. This number tell you in which order that piece of code was sent to the kernel. Because the kernel has a \"memory\", as you will see in the next section, this number can be useful so that you remember in which order the code cells in your notebook were executed. \n",
"\n",
"In the example above, the code cell contained only a single line of code, but if you want, you can include as many lines as you want in your code cell:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(\"Hello\")\n",
"print(\"world\")\n",
"print(\"Goodbye\")"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-8698bcb51f5ce066",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"In the above, the text in the code cell are all python commands. In addition, if you start a line in a code cell with a `#`, python will ignore this line of text. This is use to add **comments** to your code. It is good programming practice to use comments to explain what the code is doing:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# This will print out a message\n",
"print(\"This is a message\")"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-4919a733b4210f11",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"**Exercise 1.1** Print your own string to the command line. Can you use special characters as well?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"### BEGIN SOLUTION\n",
"print(\" df# \")\n",
"### END SOLUTION"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-74c3c19c58006da4",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"## The Python kernel has a memory\n",
"\n",
"In addition to asking python to do things for you, like the \"Hello world\" example above, you can also have python remember things for you. To do this, you can use the following syntax:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 5"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-84c1e3509c93658b",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"In python, the `=` symbol represents the **assignment operator**: it is an instruction to **assign** the value of `5` to the variable `a`. If variable `a` already exists, it will be over-written with the new value (in fact, `a` is a python object, something that we will explain in the optional notebook in more detail). If variable `a` does not yet exist, then python will create a new variable for you automatically.\n",
"\n",
"For you, the cell above will create a \"variable\" named `a` in memory of the python kernel that has the value of 5. We can check this by printing the value of a:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"print(a)"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-99b80d998fcc74ff",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"Besides numerical values variables can also be strings, which are sequences of characters. You make a string by putting the text between quotes.\n",
"\n",
"Note that we can also add a message if we add a string and a numerical value in the `print()` statement by combining things with commas:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(\"The value of a is\",a)"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-a4382a92b6e9aeec",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"**Exercise 1.2** Combine multiple strings and numerical values in a single `print` statement using the `,` separator."
]
},
{
"cell_type": "code",
"metadata": {
"ExecuteTime": {
"end_time": "2020-08-21T14:33:20.498051Z",
"start_time": "2020-08-21T14:33:20.472191Z"
}
},
Gary Steele
committed
"outputs": [],
"source": [
Gary Steele
committed
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-cbf03d005dae5d5d",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"**Exercise 1.3** Change the value of `a` to 7 by executing the following cell, and then re-run the **above** cell containing the command `print(a)` (the one with output `5`). What value gets printed now in that cell? "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# your code here to assign the value 7 to variable a"
Gary Steele
committed
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-2b713ce46a7bca48",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"As you can see in notebooks that the location of your code doesn’t matter, but the order in which you execute them does!!\n",
"\n",
"We can also use variables to set the values of other variables:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"b = 0\n",
"print(b)\n",
"b = a \n",
"print(b)"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-16240c968680ffa4",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"Sometimes, if you execute a lot of cells, or maybe even re-execute a cell after changing its contents, you might lose track of what variables are defined in the memory of your python kernel. For this, there is a convenient built-in \"magic\" command called `%whos` that can list for you all the variables that have been defined in your kernel, along with their values:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a=5 \n",
"%whos"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-d61c3a57fbd93ed6",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
"source": [
"_(Some notes about `%whos`: `%whos` is not a \"native\" command of the python language, but instead a \"built-in\" command that has been added by the creators of Jupyter. Because of this, you cannot use it outside of Jupyter / iPython...)_\n",
"\n",
"If we define some new variables, they will also appear in the list of defined variables if you execute `%whos`:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"c = 10\n",
"d = 15.5"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%whos"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-bea496517f99df02",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"In this case the variable named is displayed, its value, but also its type. Type defines the format in which a variable is stored in memory. In this case `int` stands for integer and `float` stands for floating point number, which is the usual way in which real numbers are stored in a computer. We will learn more about Python variable types below."
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-80d1461986f4d365",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
"source": [
"## Starting and stopping the kernel\n",
"\n",
"When you open a notebook for the first time, a new kernel will be started for you, which will have nothing in your memory. \n",
"\n",
"Important to understand: if you close the tab of your browser that has the notebook, Jupyter **will not** shut down the kernel! It will leave the kernel running and when you re-open the notebook in your browser, all the variables you defined will still be in the memory. You can test this by closing this notebook right now, clicking on the link to open it in the \"tree\" file browser tab of Jupyter, and then re-running the cell above with the command `%whos`. \n",
"\n",
"How do I shutdown a kernel? And how do I know if a notebook on my computer already has a kernel running? \n",
"\n",
"* First, as you may have noticed, when you closed this notebook and went back to the \"tree\" file brower, the notebook icon had turned green. This is one way that Jupyter tells you that a notebook file has a running kernel.\n",
"\n",
"* Second: in the <a href=\".\"> \"tree\" view </a> of the Jupyter interface, there is a link at the top to a tab \"Running\" that will show you all the running kernels and allow you to stop them manually. \n",
"\n",
"Sometimes, you may want to restart the kernel of a notebook you are working on. You may want to do this to clear all the variables and run all your code again from a \"fresh start\" (which you should always do before submitting an assignment!). You may also need to do this if your kernel crashes (the \"status\" of your kernel can be seen in the icons at the right-hand side of the Jupyter menu bar at the top of the screen). \n",
"\n",
"For this, there is both a menubar \"Kernel\" at the top, along with two useful buttons in the toolbar: \n",
"\n",
"* \"Stop\": tells the kernel to abort trying to run the code it is working on, but does not erase its memory\n",
"* \"Restart\": \"kill\" the kernel (erasing its memory), and start a new one attached to the notebook.\n",
"\n",
"<img src=\"resource/asnlib/public/Notebook_1_stop_button.png\" width=20%></img>\n",
"<img src=\"resource/asnlib/public/Notebook_1_restartkernelmenu.png\" width=60%></img>\n",
"\n",
"To see this in action, you can execute the following cell, which will do nothing other than wait for 10 minutes:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": false
},
"outputs": [],
"source": [
"from time import sleep\n",
"sleep(10*60)"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-6c0352859b13ed82",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"You will notice that while a cell is running, the text beside it shows `In [*]:`. The `*` indicates that the cell is being executed, and will change to a number when the cell is finished. You will also see that the small circle beside the `Python 3` text on the right side of the Jupyter menu bar at the top of the page will become solid. Unless you have a lot of patience, you should probably stop the kernel, using the \"Stop\" button, or the menu item \"Kernel / Interrupt\".\n",
"\n",
"**Exercise 1.4** List the stored variables using the `%whos` command. Subsequently, restart the kernel. What variables are stored in the memory of the kernel before and after the restart? "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"# add your code to exectue the command %whos here, then restart the kernel and run this cell again"
Gary Steele
committed
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-fd74d0d65cf02f0a",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"## Python variable types\n",
"\n",
"As we saw above, in Python, variable have a property that is called their \"type\". When you use the assignment operator `=` to assign a value to a variable, python will automatically pick a variable type it thinks fits best, even changing the type of an existing variable if it thinks it is a good idea. \n",
"\n",
"You have, in fact, already seen information about the types of variables in the `%whos` command again:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"%whos"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-6f2bfadc72282277",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
"source": [
"In the second column, you can see the **type** that python chose for the variables we created. `int` corresponds to integer numbers, `float` corresponds to floating-point numbers. You can see that for variable `c`, python had to choose a `float` type (because 15.5 is not an integer), but for `a` and `b`, it chose integer types. \n",
"\n",
"_(In general, Python tries to choose a variable type that makes calculations the fastest and uses as little memory as possible.)_\n",
"\n",
"If you assign a new value to a variable, it can change the variables type:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = a/2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"%whos"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-8ac075dfca80d989",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"Because 5/2 = 2.5, Python decided to change the type of variable `a` from `int` to `float` after the assignment operation `a = a/2`. \n",
"\n",
"When you are using floating point numbers, you can also use an \"exponential\" notation to specify very big or very small numbers: "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"c = 1.5e-8"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-9f4aa0b51687698a",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
"source": [
"The notation `1.5e-8` is a notation used in python to indicate the number $1.5 \\times 10^{-8}$.\n",
"\n",
"A third type of mathematical variable type that you may use in physics is a complex number. In python, you can indicate a complex number by using `1j`, which is the python notation for the complex number $i$:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"d = 1+1j"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%whos"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-212eb128ab19078d",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"The notation `1j` is special, in particular because there is **no space** between the number `1` and the `j`. This is how Python knows that you are telling it to make a complex number (and not just referring to a variable named `j`...). The number in front of the `j` can be any floating point number: for example,"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"ExecuteTime": {
"end_time": "2020-08-21T14:57:37.501905Z",
"start_time": "2020-08-21T14:57:37.486365Z"
}
},
Gary Steele
committed
"outputs": [],
"source": [
Gary Steele
committed
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-770f5a2d267d39b4",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
"source": [
"In addition to the mathematical variable types listed above, there are also other types of variables in Python. A common one you may encounter is the \"string\" variable type `str`, which is used for pieces of text. To tell Python you want to make a string, you enclose the text of your string in either single forward quotes `'` or double forward quotes `\"`:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"e = \"This is a string\"\n",
"f = 'This is also a string'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%whos\n",
"print(e)\n",
"print(f)"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-6e76757478040b18",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"You can also make multiline strings using three single quotes:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"multi = \\\n",
"'''\n",
"This string\n",
"has \n",
"multiple lines.\n",
"'''\n",
"print(multi)"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-31e4b55de81cef07",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"Note here that I have used a backslash: this a way to split Python code across multiple lines. \n",
"\n",
"Although it's not obvious, Python can also do \"operations\" on strings, the `+` mathematical opeartors we saw above also works with strings. \n",
"\n",
"**Exercise 1.5** Discover what the `+` operator does to a string, i.e. print the output of the sum of two strings."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
Gary Steele
committed
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-1fa7be3de8eb7f5a",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
"source": [
"There is one more useful variable type we will introduce here: the \"boolean\" type `bool`. Boolean variable can have two values: `True` and `False`. You type them in directly as `True` and `False` with no quotes (you will see them turn green). "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"g = 0"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": false
},
"outputs": [],
"source": [
"%whos"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-12ff71b21d9d01e3",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
"source": [
"We will use boolean types much more later when we look at program control flow, but a simple example using the `if` statement is given below: \n",
"\n",
"No panic if you don't yet understand the if statement, there will be another entire notebook dedicated to them. This is just an example of why boolean variables exist."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"if True:\n",
" print(\"True is always true.\")\n",
"\n",
"if g:\n",
" print(\"g is true!\")\n",
" \n",
"if not g:\n",
" print(\"g is not true!\")"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-7f2acb9e44b581d8",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"You can try changing the value of `g` above to `False` and see what happens if you run the above code cell again.\n",
"\n",
"Also, useful to know: numbers (both `int` and `float`) can also be used in True / False statements! Python will interpret any number that is not zero as `True` and any number that is zero as `False`. "
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-4016c53a455f3656",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"**Exercise 1.6** Discover which numbers can be used as `True` and `False` in Python by changing the value of `g` above and re-running the cells."
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-c1323d47dae023f1",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
"source": [
"## Converting variables between different types\n",
"\n",
"We can also convert a value from one type to another by using functions with the same name as the type that we want to convert them to. Some examples:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"float(5)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"int(7.63)"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-e7f8cf2c018ef4fd",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
"source": [
"Note that when converting an `float` to an `int`, python does not round off the value, but instead drops all the numbers off after the decimal point (it \"trucates\" it). If we want to convert to an integer and round it off, we can use the `round()` function:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"b = round(7.63)\n",
"print(b)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"type(b)\n",
"print(b+0.4)"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-f3f5149b2d627e26",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"This works for conversions between many types. Sometimes, you have will lose information in this process: for example, converting a `float` to an `int`, we lose all the numbers after the decimal point. In this example, Python makes a guess at what you probably want to do, and decides to round off the floating point number to the nearest integer. \n",
"\n",
"Sometimes, Python can't decide what to do, and so it triggers an error:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"float(1+1j)"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-582c3f589fac8746",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},
Gary Steele
committed
"source": [
"A very useful feature is that Python can convert numbers into strings:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"a = 7.54\n",
"str(a)\n",
"b = a + 1\n",
"print(b)\n",
"%whos"
]
},
{
"cell_type": "markdown",
Gary Steele
committed
"metadata": {
"nbgrader": {
"grade": false,
"grade_id": "cell-18152675870ab0f1",
"locked": true,
"schema_version": 3,
"solution": false,
"task": false
}
},