Editing Intro to Programming and Data Science (Summer 2020)/Day 1 Tutorial

From CommunityData

Warning: You are not logged in. Your IP address will be publicly visible if you make any edits. If you log in or create an account, your edits will be attributed to your username, along with other benefits.

The edit can be undone. Please check the comparison below to verify that this is what you want to do, and then publish the changes below to finish undoing the edit.

Latest revision Your text
Line 2: Line 2:


This tutorial introduces several core programming concepts that we'll build upon through the coming weeks. It will take 1-2 hours to complete. There's a break in the middle, and exercises at the middle and end to help review the material.
This tutorial introduces several core programming concepts that we'll build upon through the coming weeks. It will take 1-2 hours to complete. There's a break in the middle, and exercises at the middle and end to help review the material.
To get started, fire up a new Jupyter notebook. Name it as you like.
[[File:Creating a python notebook in Jupyter.png|frame|From the Jupyter page, where you should look to create a python notebook!]]


This is an interactive tutorial! As you go through this tutorial, any time you see something that looks like this:
This is an interactive tutorial! As you go through this tutorial, any time you see something that looks like this:


<syntaxhighlight lang="python">
  a = "Hello"
  a = "Hello"
</syntaxhighlight>


you should type the expression in a new cell of your Jupyter notebook (found in the 'Insert' menu), then hold Shift and hit Return (or Enter) after every line and check the output, making sure it matches your expectations.
you should type the expression at a '''Python''' prompt in the terminal, hitting Return after every line and noting the output.


Unless otherwise noted, you should try not to copy and paste! You'll learn the concepts better if you type them out yourself.
No copying and pasting! You'll learn the concepts better if you type them out yourself.


==Math==  
==Math==  
Line 22: Line 15:
[[File:Calculator.png|100px]]
[[File:Calculator.png|100px]]


Math in Python looks a lot like math you type into a calculator. A Jupyter notebook makes a great calculator if you need to crunch some numbers and don't have a good calculator handy.
Math in Python looks a lot like math you type into a calculator. A Python prompt makes a great calculator if you need to crunch some numbers and don't have a good calculator handy.


===Addition===
===Addition===


<syntaxhighlight lang="python">
  2 + 2
  2 + 2</syntaxhighlight>
<syntaxhighlight lang="python">
 
  1.5 + 2.25
  1.5 + 2.25
</syntaxhighlight>


===Subtraction===
===Subtraction===
<syntaxhighlight lang="python">
4 - 2</syntaxhighlight>
<syntaxhighlight lang="python">
100 - .5</syntaxhighlight>
<syntaxhighlight lang="python">


4 - 2
100 - .5
  0 - 2
  0 - 2
</syntaxhighlight>


===Multiplication===
===Multiplication===
<syntaxhighlight lang="python">
 
  2 * 3
  2 * 3
</syntaxhighlight>
 
===Division===
===Division===


First, lets try some basic fractions:
4 / 2
 
<syntaxhighlight lang="python">
  1 / 2
  1 / 2
</syntaxhighlight>
 
If you were doing some baking and needed to add 3/4 of a cup of flour and 1/4 of a cup of flour, we know in our heads that 3/4 + 1/4 = 1 cup. Try that at the Python prompt:
Sure enough, Python says that the answer is 0.5 which is the same as 1/2.


Let's try the same thing:
  3/4 + 1/4
 
<syntaxhighlight lang="python">
  4 / 2
</syntaxhighlight>
 
Hey now! That last result is a little strange. When you divide a number in Python, even if the answer doesn't need a decimal place (like <code>4/2</code> which equals 2), you get an answer with a decimal point!
 
What's going on here is that in Python, division produces an what's called a <code>float</code> which essentially means a number with a decimal point.
 
When the Python interpreter goes to do the division, it knows that (unlike multiplication for example) division can lead to numbers that aren't whole numbers (like <code>1/2</code>) so it makes sure that the result will always include a decimal place just in case it's needed.
 
 
This shouldn't be important for this class but it might be worth knowing that older versions of Python (before version 3) would always round down and return integers instead of giving numbers with decimal places.


==Types==
==Types==
Line 78: Line 46:


There's a helpful '''function''' (more on what a function is in a second) called <code>type</code> that tells you what kind of thing -- what '''data type''' -- Python thinks something is. We can check for ourselves that Python considers '1' and '1.0' to be different data types:
There's a helpful '''function''' (more on what a function is in a second) called <code>type</code> that tells you what kind of thing -- what '''data type''' -- Python thinks something is. We can check for ourselves that Python considers '1' and '1.0' to be different data types:
<syntaxhighlight lang="python">
type(1)</syntaxhighlight>
<syntaxhighlight lang="python">


type(1)
  type(1.0)
  type(1.0)
</syntaxhighlight>
So now we've seen two data types: '''integers''' and '''floats'''. Python tags your variables with a data type to make better guesses about what you want and to prevent errors. Another data type you'll run into is strings (a sequence of letters, numbers, and symbols, like the ones you're reading right now -- we'll look at strings a bit more in a moment).
So now we've seen two data types: '''integers''' and '''floats'''.


What's a "function"? Here are the important ideas about functions:


* A function encapsulates (packages up) a useful bit of work and gives that work a name.
By the way, what is a "function"? We will talk a lot more about functions later but here are the important ideas about what they are:
* You provide input to a function and it produces output. For example, the <code>type</code> function takes data as an input, and produces what type of data the data is (e.g. an integer or a float) as output.
 
* To use a function, write the name of the function, followed by an open parenthesis, then what the function needs as input (we call that input the '''arguments''' to the function), and then a close parenthesis.
* A function encapsulates a useful bit of work and gives that work a name.
* Programmers have a lot of slang around functions. They'll say that functions "take" arguments, or that they "give" or "pass" arguments to a function. "call" and "invoke" are both synonyms for using a function.
* You provide input to a function and it produces output. For example, the <code>type</code> function takes data as an input, and produces what type of data the input is (e.g. an integer or a float) as output.
* To use a function, write the name of the function, followed by an open parenthesis, then what the function needs as input (we call the input the '''arguments''' to the function), and then a closing parenthesis.
* Programmers have a lot of slang around functions. They'll say that functions "take" arguments, or that they "give" or "pass" arguments to a function. When they use a function they might describe that as "calling" or "invoking" it.


In the example above, "type" was the name of the function. <code>type</code> takes one argument; we first gave <code>type</code> an argument of 1 and then gave it an argument of 1.0.
In the example above, "type" was the name of the function. <code>type</code> takes one argument; we first gave <code>type</code> an argument of 1 and then gave it an argument of 1.0.
Line 99: Line 66:
[[File:Function_diagram.png]]
[[File:Function_diagram.png]]


===Jupyter history===
===Command history===


In your Jupyter notebook, any time you want to re-run a command, you can select that cell again and repeat the same Shift+Enter action to re-run the cell.
Stop here and try hitting the Up arrow on your keyboard a few times. The Python '''interpreter''' saves a history of what you've entered, so you can arrow up to old commands and hit Return to re-run them!


==Variables==
==Variables==
Line 107: Line 74:
[[File:Fraction.png|100px]]
[[File:Fraction.png|100px]]


A lot of work gets done in Python using variables. Variables are a lot like the variables in math class, except that in Python variables can be of any data type, not just numbers.
Variables are a lot like the variables in math class, but instead of trying to figure out what the value is that a variable represents, you create variables and use them to store data. For example, in the following code we store the number 4 as the variable <code>x</code>.
<syntaxhighlight lang="python">
type(4)</syntaxhighlight>
<syntaxhighlight lang="python">


type(4)
  x = 4
  x = 4
</syntaxhighlight>
<syntaxhighlight lang="python">
  x
  x
</syntaxhighlight>
<syntaxhighlight lang="python">
  type(x)
  type(x)
</syntaxhighlight>
<syntaxhighlight lang="python">
  2 * x
  2 * x
</syntaxhighlight>
 
Giving a name to something, so that you can refer to it by that name, is called '''assignment'''. Above, we assigned the name 'x' to 4, and after that we can use <code>x</code> wherever we want to use the number 4. You'll see that there wasn't any output here when you ''assigned'' 4 to <code>x</code>; that's fine! Not all Python operations have output, and in fact most of the time that's what you expect.
The expression <code>x = 4</code> is called '''assignment'''. This is when we create a variable and assign a valued to it. Above, we assigned the name 'x' to 4, and after that we can use <code>x</code> wherever we want to use the number 4.


Variables can't have spaces or other special characters, and they need to start with a letter. Here are some valid variable names:
Variables can't have spaces or other special characters, and they need to start with a letter. Here are some valid variable names:
<syntaxhighlight lang="python">
magic_number = 1500
amountOfFlour = .75
my_name = "Jessica"
</syntaxhighlight>


Projects develop naming conventions: maybe multi-word variable names use underscores (like <code>magic_number</code>), or "camel case" (like <code>amountOfFlour</code>). The most
<code>magic_number = 1500</code><br />
important thing is to be consistent within a project, because it makes the code more readable.
<code>amountOfFlour = .75</code><br />
<code>my_name = "Jessica"</code>
 
Projects develop naming conventions: maybe multi-word variable names use underscores (like <code>magic_number</code>), or "camel case" (like <code>amountOfFlour</code>). The most important thing is to be consistent within a project, because it makes the code more readable.
 


==Output==
==Output==


[[File:Pacman.png|100px]]


Notice how if you type a 4 and hit enter, the Python interpreter spits a 4 back
Notice how if you type a 4 and hit enter, the Python interpreter spits a 4 back
out:
out:
<syntaxhighlight lang="python">
 
  4
  4
</syntaxhighlight>
 
But if you assign 4 to a variable, nothing is printed:
But if you assign 4 to a variable, nothing is printed:
<syntaxhighlight lang="python">
 
  x = 4
  x = 4
</syntaxhighlight>
You can think of it as that something needs to get the output. Without an assignment, the winner is the screen. With assignment, the output goes to the variable.


You can reassign variables if you want. What do you think will print if you type in:
You can think of the output as needing to go somewhere. When it isn't assigned to a variable, the output goes to the screen. With assignment, the output goes to the variable instead.
<syntaxhighlight lang="python">
x = 4</syntaxhighlight>
<syntaxhighlight lang="python">


You can change the value that a variable holds:
x = 4
  x
  x
</syntaxhighlight>
<syntaxhighlight lang="python">
  x = 5
  x = 5
</syntaxhighlight>
<syntaxhighlight lang="python">
  x
  x
</syntaxhighlight>
 
Sometimes reassigning a variable is an accident and causes bugs in programs.
Sometimes reassigning a variable is an accident and causes bugs in programs.
<syntaxhighlight lang="python">
 
  x = 3
  x = 3
</syntaxhighlight>
<syntaxhighlight lang="python">
  y = 4
  y = 4
</syntaxhighlight>
<syntaxhighlight lang="python">
  x * y
  x * y
</syntaxhighlight>
<syntaxhighlight lang="python">
  x * x
  x * x
</syntaxhighlight>
<syntaxhighlight lang="python">
  2 * x - 1 * y
  2 * x - 1 * y
</syntaxhighlight>
 
Order of operations works pretty much like how you learned in school. If you're unsure of an ordering, you can add parentheses like on a calculator:
Order of operations works pretty much like how you learned in school. If you're unsure of an ordering, you can add parentheses like on a calculator:
<syntaxhighlight lang="python">
 
  (2 * x) - (1 * y)
  (2 * x) - (1 * y)
</syntaxhighlight>
 
Note that the spacing doesn't matter:
Note that the spacing doesn't matter:
<syntaxhighlight lang="python">
 
  x = 4
  x = 4
</syntaxhighlight>
 
and
and
<syntaxhighlight lang="python">
 
  x=4
  x=4
</syntaxhighlight>
 
are both valid Python and mean the same thing.
are both valid Python and mean the same thing.
<syntaxhighlight lang="python">
 
  (2 * x) - (1 * y)
  (2 * x) - (1 * y)
</syntaxhighlight>
 
and
and
<syntaxhighlight lang="python">
 
  (2*x)-(1*y)
  (2*x)-(1*y)
</syntaxhighlight>
 
are also both valid and mean the same thing. You should strive to be consistent with whatever spacing you like or a job requires, since it makes reading the code easier.
are also both valid and mean the same thing. You should strive to be consistent with whatever spacing you like or a job requires, since it makes reading the code easier.


Line 209: Line 151:


So far we've seen two data types: '''integers''' and '''floats'''. Another useful data type is a '''string''', which is just what Python calls a bunch of characters (like numbers, letters, whitespace, and punctuation) put together. Strings are indicated by being surrounded by quotes:
So far we've seen two data types: '''integers''' and '''floats'''. Another useful data type is a '''string''', which is just what Python calls a bunch of characters (like numbers, letters, whitespace, and punctuation) put together. Strings are indicated by being surrounded by quotes:
<syntaxhighlight lang="python">
 
If you try to type a string without surrounding it with quotes, Python will think you're trying to reference a variable. Try this:
 
hello
 
You will get an error message like:
 
>>> hello
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'hello' is not defined
 
Python is giving us a '''traceback'''. A traceback is details on what was happening when Python encountered an Exception or Error -- something it doesn't know how to handle.
 
There are many kinds of Python errors, with descriptive names to help us humans understand what went wrong. In this case we are getting a <code>NameError</code>: Python can't find something that it thinks should be there. In this case, the variable <code>hello</code>.
 
 
Now, try with quote marks:
 
  "Hello"
  "Hello"
</syntaxhighlight>
<syntaxhighlight lang="python">
  "Python, I'm your #1 fan!"
  "Python, I'm your #1 fan!"
</syntaxhighlight>
 
Like with the math data types above, we can use the <code>type</code> function to check the type of strings:
Like with the math data types above, we can use the <code>type</code> function to check the type of strings:
<syntaxhighlight lang="python">
 
  type("Hello")
  type("Hello")
</syntaxhighlight>
<syntaxhighlight lang="python">
  type(1)
  type(1)
</syntaxhighlight>
<syntaxhighlight lang="python">
  type("1")
  type("1")
</syntaxhighlight>
 
===String Concatenation===
===String Concatenation===


You can smoosh strings together (called "concatenation") using the '+' sign:
You can combine strings together (called "concatenation") using the '+' sign:
<syntaxhighlight lang="python">
 
  "Hello" + "World"
  "Hello" + "World"
</syntaxhighlight>
<syntaxhighlight lang="python">


  name = "Jessica"
  name = "Jessica"
  "Hello " + name
  "Hello " + name
</syntaxhighlight>
 
How about concatenating different data types?
How about concatenating different data types?
<syntaxhighlight lang="python">
 
  "Hello" + 1
  "Hello" + 1
</syntaxhighlight>
Hey now! The output from the previous example was really different and interesting; let's break down exactly what happened: (you'll see a ''slightly'' different "Traceback" statement, that difference doesn't matter.)
<pre>
In[ ]: "Hello" + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
</pre>


Python is giving us a '''traceback'''. A traceback is details on what was happening when Python encountered an Exception or Error -- something it doesn't know how to handle.
Hey now! The output from the previous example was really different and interesting; let's break down exactly what happened:


There are many kinds of Python errors, with descriptive names to help us humans understand what went wrong. In this case we are getting a <code>TypeError</code>: we tried to do some operation on a data type that isn't supported for that data type.
<code>>>> "Hello" + 1</code><br />
<code>Traceback (most recent call last):</code><br />
<code>  File "<stdin>", line 1, in <module></code><br />
<code>TypeError: cannot concatenate 'str' and 'int' objects</code>


Python gives us a helpful error message as part of the TypeError:
Again, we get a Traceback. This time, Python gives us a helpful error message as part of the TypeError:


<code>"cannot concatenate 'str' and 'int' objects"</code>
<code>"cannot concatenate 'str' and 'int' objects"</code>


We saw above that we can concatenate strings:
We saw above the we can concatenate strings:


  "Hello" + "World"
  "Hello" + "World"
Line 267: Line 213:
  "Hello" + 1
  "Hello" + 1


produces a <code>TypeError</code>. We are telling Python to concatenate a string and an integer, and that's not something Python understands how to do.
produces a <code>TypeError</code> because we are telling Python to concatenate a string and an integer, and that's not something Python understands how to do.


We can convert an integer into a string ourselves, using the <code>str</code> function:
We can convert an integer into a string ourselves, using the <code>str</code> function:
Line 279: Line 225:
There's another useful function that works on strings called <code>len</code>. <code>len</code> returns the length of a string as an integer:
There's another useful function that works on strings called <code>len</code>. <code>len</code> returns the length of a string as an integer:


<syntaxhighlight lang="python">
  len("Hello")
  len("Hello")
</syntaxhighlight>
  len("")
<syntaxhighlight lang="python">
  len("")</syntaxhighlight>
<syntaxhighlight lang="python">
 
  fish = "humuhumunukunukuapua'a"
  fish = "humuhumunukunukuapua'a"
</syntaxhighlight>
<syntaxhighlight lang="python">
  name_length = len(fish)
  name_length = len(fish)
</syntaxhighlight>
<syntaxhighlight lang="python">
  fish + " is a Hawaiian fish whose name is " + str(name_length) + " characters long."
  fish + " is a Hawaiian fish whose name is " + str(name_length) + " characters long."
</syntaxhighlight>


===Quotes===
===Quotes===


We've been using double quotes around our strings, but you can use either double or single quotes:
We've been using double quotes around our strings, but you can use either double or single quotes:
<syntaxhighlight lang="python">
 
  'Hello'
  'Hello'
  "Hello"
  "Hello"
</syntaxhighlight>
 
Like with spacing above, use whichever quotes make the most sense for you, but be consistent.
Like with spacing above, use whichever quotes make the most sense for you, but be consistent.


Line 319: Line 255:


One fun thing about strings in Python is that you can multiply them:
One fun thing about strings in Python is that you can multiply them:
<syntaxhighlight lang="python">
"A" * 40</syntaxhighlight>
<syntaxhighlight lang="python">


  "ABC" * 12</syntaxhighlight>
  "A" * 40
<syntaxhighlight lang="python">
"ABC" * 12
  h = "Happy"
  h = "Happy"
  b = "Birthday"
  b = "Birthday"
  (h + b) * 10
  (h + b) * 10
</syntaxhighlight>


==Part 1 Practice==
==Part 1 Practice==
Line 334: Line 266:
[[File:Detective.png|100px]]
[[File:Detective.png|100px]]


Read the following expressions, but don't execute them. Guess what the output will be. After you've made a guess, copy and paste the expressions into your Jupyter notebook and check your guess.
Read the following expressions, but don't execute them. Guess what the output will be. After you've made a guess, copy and paste the expressions at a Python prompt and check your guess.


1.
1.
<syntaxhighlight lang="python">
 
  total = 1.5 - 1/2
  total = 1.5 - 1/2
  total
  total
  print(type(total))
  type(total)
</syntaxhighlight>
 


2.
2.
<syntaxhighlight lang="python">
 
  a = "quick"
  a = "quick"
  b =  "brown"
  b =  "brown"
  c = "fox jumps over the lazy dog"
  c = "fox jumps over the lazy dog"
  print("The " +  a * 3 + " " +  b * 3 + " " + c)
  "The " +  a * 3 + " " +  b * 3 + " " + c
</syntaxhighlight>


==End of Part 1==
==End of Part 1==
Line 355: Line 286:
Congratulations! You've learned about and practiced math, strings, variables, data types, exceptions, tracebacks, and executing Python from the Python prompt.
Congratulations! You've learned about and practiced math, strings, variables, data types, exceptions, tracebacks, and executing Python from the Python prompt.


Take a break, stretch, meet some neighbors, and ask the staff if you have any questions about this material.
Take a break, stretch, meet some neighbors, and ask me if you have any questions about this material.


[[File:Fireworks.png|200px]]
[[File:Fireworks.png|200px]]
== Part 2: Printing==
So far we've been learning at the interactive '''Python interpreter'''. When you are working at the interpreter, any work that you do gets printed to the screen. For example:
h = "Hello"
w = "World"
h + w
will display "HelloWorld".
Another place that we will be writing Python code is in a file. When we run Python code from a file instead of interactively, we don't get work printed to the screen for free. We have to tell Python to print the information to the screen. The way we do this is with the '''print''' function. Here's how it works:
h = "Hello"
w = "World"
print(h + w)
my_string = "Alpha " + "Beta " + "Gamma " + "Delta"
print(my_string)
We'll see more examples of the print function in the next section.
==Python scripts==
[[File:Treasure_map.png|100px]]
Until now we've been using the interactive Python interpreter. This is great for learning and experimenting, but you can't easily save or edit your work. For bigger projects, we'll write our Python code in a file. Let's get some practice with this!
<ol>
<li>Download the file http://jeremydfoote.com/teaching/2020/intro_to_ds/nobel.py by right-clicking this link and saying to save it as a ".py" file to your Desktop. The ".py" extension hints that this is a Python script.</li>
<li>Open a terminal prompt, and use the navigation commands you should have learned earlier (<code>ls</code> and <code>cd</code>) to navigate to your Desktop directory.
<li>Once you are in your Desktop directory, execute the contents of <code>nobel.py</code> by typing
<pre>python nobel.py</pre>
at the terminal prompt.
<code>nobel.py</code> introduces two new concepts: comments and multiline strings.</li>
<li>Open <code>nobel.py</code> in your text editor.</li>
<li>Read through the file in your text editor carefully and check your understanding of both the comments and the code.</li>
</ol>
Study the script until you can answer these questions:
<ol>
<li>How do you comment code in Python?</li>
<li>How do you print just a newline?</li>
<li>How do you print a multi-line string so that whitespace is preserved?</li>
</ol>
==Booleans==
Please return to the interactive Python interpreter for the rest of the tutorial. And remember: type out the examples. You'll thank yourself tomorrow. :)
[[File:Scales.png|100px]]
So far, the code we've written has been <i>unconditional</i>: no choice is getting made, and the code is always run. Python has another data type called a '''boolean''' that is helpful for writing code that makes decisions. There are two booleans: <code>True</code> and <code>False</code>.
True
type(True)
False
type(False)
You can test if Python objects are equal or unequal. The result is a boolean:
0 == 0
0 == 1
Use <code>==</code> to test for equality. Recall that <code>=</code> is used for <i>assignment</i>.
This is an important idea and can be a source of bugs until you get used to it: '''= is assignment, == is comparison'''.
Use <code>!=</code> to test for inequality:
"a" != "a"
"a" != "A"
<code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code> have the same meaning as in math class. The result of these tests is a boolean:
1 > 0
2 >= 3
-1 < 0
.5 <= 1
You can check for containment with the <code>in</code> keyword, which also results in a boolean:
"H" in "Hello"
"X" in "Hello"
Or check for a lack of containment with <code>not in</code>:
"a" not in "abcde"
"Perl" not in "Python Workshop"


==Making choices==
==Making choices==
Line 372: Line 408:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>print("Six is greater than five!")</code>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>print("Six is greater than five!")</code>


That is our first multi-line piece of code, and the way to type it into a Jupyter notebook is a little different. Let's break down how to do this (type this out step by step):
That is our first multi-line piece of code, and the way to type it at a Python prompt is a little different. Let's break down how to do this (type this out step by step):
 
First, type the <code>if 6 > 5:</code>, then hit enter. ''Not'' Shift + Enter, because this time we want to write more than one line before we ask Jupyter to run it!
 
Once you've hit enter, you'll see that your carat is indented already for you; Jupyter understands that you're now inside the <code>if</code> ''code block'', and adjusts your indentation position for you. In Python, all lines of a block are at the same indentation level, and the block ends when you reduce your indentation again.


Write <code>print("Six is greater than five!")</code>, then hit enter, and now hit Shift+Enter to run this if statement!
<ol>
<ol>
<li>First, type the<br />
<li>First, type the<br />
Line 384: Line 415:
&nbsp;&nbsp;&nbsp;&nbsp;<code>if 6 > 5:</code><br />
&nbsp;&nbsp;&nbsp;&nbsp;<code>if 6 > 5:</code><br />
<br />
<br />
part, and press Enter. <!-- The next line will have <code>...</code> as a prompt, instead of the usual <code>&gt;&gt;&gt;</code>. This is Python telling us that we are in the middle of a '''code block''', and so long as we indent our code it should be a part of this code block. -->.</li>
part, and press Enter. The next line will have <code>...</code> as a prompt, instead of the usual <code>&gt;&gt;&gt;</code>. This is Python telling us that we are in the middle of a '''code block''', and so long as we indent our code it should be a part of this code block.</li>


<!-- li>Press the spacebar 4 times to indent.</li -->
<li>Press the spacebar 4 times to indent.</li>
<li>You'll notice that your text caret (|) will be indented by four spaces. This is important, and it tells python that you're telling it what to do with your if statement.</li>
<li>Type<br />
<li>Type<br />
<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;<code>print("Six is greater than five!")</code><br /><br /></li>
&nbsp;&nbsp;&nbsp;&nbsp;<code>print("Six is greater than five!")</code><br /><br /></li>
<!-- li>Press Enter to end the line. The prompt will still be a <code>...</code></li -->
<li>Press Enter to end the line. The prompt will still be a <code>...</code></li>
<li>Press shift-enter to tell Jupyter to run that block of code.</li>
<li>Press Enter one more time to tell Python you are done with this code block. The code block will now execute.</li>
</ol>
</ol>


Line 398: Line 428:


<pre>
<pre>
if 6 > 5:
>>> if 6 > 5:
     print("Six is greater than five!")
...     print("Six is greater than five!")
 
...
Six is greater than five!
Six is greater than five!
</pre>
</pre>
Line 424: Line 454:
Use the '''<code>else</code>''' keyword, together with <code>if</code>, to execute different code when the <code>if</code> condition isn't <code>True</code>. Try this:
Use the '''<code>else</code>''' keyword, together with <code>if</code>, to execute different code when the <code>if</code> condition isn't <code>True</code>. Try this:


<syntaxhighlight lang="python">
<pre>
sister_age = 15
sister_age = 15
brother_age = 12
brother_age = 12
Line 431: Line 461:
else:
else:
     print("brother is older")
     print("brother is older")
</syntaxhighlight>
</pre>


Like with <code>if</code>, the code block under the <code>else</code> condition must be indented so Python knows that it is a part of the <code>else</code> block.
Like with <code>if</code>, the code block under the <code>else</code> condition must be indented so Python knows that it is a part of the <code>else</code> block.
Line 441: Line 471:
Try typing these out and see what you get:
Try typing these out and see what you get:


<syntaxhighlight lang="python">
<pre>
1 > 0 and 1 < 2
1 > 0 and 1 < 2
</syntaxhighlight>
</pre>


<syntaxhighlight lang="python">
<pre>
1 < 2 and "x" in "abc"
1 < 2 and "x" in "abc"
</syntaxhighlight>
</pre>


<syntaxhighlight lang="python">
<pre>
"a" in "hello" or "e" in "hello"
"a" in "hello" or "e" in "hello"
</syntaxhighlight>
</pre>


<syntaxhighlight lang="python">
<pre>
1 <= 0 or "a" not in "abc"
1 <= 0 or "a" not in "abc"
</syntaxhighlight>
</pre>


Guess what will happen when you enter these next two examples, and then type them out and see if you are correct. If you have trouble with the indenting, call over a staff member and practice together. It is important to be comfortable with indenting for tomorrow.
Guess what will happen when you enter these next two examples, and then type them out and see if you are correct. If you have trouble with the indenting, call over a staff member and practice together. It is important to be comfortable with indenting for tomorrow.


<syntaxhighlight lang="python">
<pre>
temperature = 32
temperature = 32
if temperature > 60 and temperature < 75:
if temperature > 60 and temperature < 75:
Line 465: Line 495:
else:
else:
     print("Too extreme for me.")
     print("Too extreme for me.")
</syntaxhighlight>
</pre>


<syntaxhighlight lang="python">
<pre>
hour = 11
hour = 11
if hour < 7 or hour > 23:
if hour < 7 or hour > 23:
Line 475: Line 505:
     print("Welcome to the cheese shop!")
     print("Welcome to the cheese shop!")
     print("Can I interest you in some choice gouda?")
     print("Can I interest you in some choice gouda?")
</syntaxhighlight>
</pre>


You can have as many lines of code as you want in <code>if</code> and <code>else</code> blocks; just make sure to indent them so Python knows they are a part of the block.
You can have as many lines of code as you want in <code>if</code> and <code>else</code> blocks; just make sure to indent them so Python knows they are a part of the block.
Line 483: Line 513:
If you need to execute code conditional based on more than two cases, you can use the '''<code>elif</code>''' keyword to check more cases. You can have as many <code>elif</code> cases as you want; Python will go down the code checking each <code>elif</code> until it finds a <code>True</code> condition or reaches the default <code>else</code> block.
If you need to execute code conditional based on more than two cases, you can use the '''<code>elif</code>''' keyword to check more cases. You can have as many <code>elif</code> cases as you want; Python will go down the code checking each <code>elif</code> until it finds a <code>True</code> condition or reaches the default <code>else</code> block.


<syntaxhighlight lang="python">
<pre>
sister_age = 15
sister_age = 15
brother_age = 12
brother_age = 12
Line 492: Line 522:
else:
else:
     print("brother is older")
     print("brother is older")
</syntaxhighlight>
</pre>


You don't have to have an <code>else</code> block, if you don't need it. That just means there isn't default code to execute when none of the <code>if</code> or <code>elif</code> conditions are <code>True</code>:
You don't have to have an <code>else</code> block, if you don't need it. That just means there isn't default code to execute when none of the <code>if</code> or <code>elif</code> conditions are <code>True</code>:


<syntaxhighlight lang="python">
<pre>
color = "orange"
color = "orange"
if color == "green" or color == "red":
if color == "green" or color == "red":
Line 504: Line 534:
elif color == "pink":
elif color == "pink":
   print("Valentine's Day color!")
   print("Valentine's Day color!")
</syntaxhighlight>
</pre>


If color had been "purple", that code wouldn't have printed anything.
If color had been "purple", that code wouldn't have printed anything.
Line 516: Line 546:
[[File:If-elif-else.png]]
[[File:If-elif-else.png]]


Do you understand the difference between <code>elif</code> and <code>else</code>? When do you indent? When do you use a colon? If you're not sure, talk about it with a neighbor or staff member.
Do you understand the difference between <code>elif</code> and <code>else</code>? When do you indent? When do you use a colon? If you're not sure, talk about it with a neighbor or with me.
 
==Booleans==
 
Please return to the interactive Python interpreter for the rest of the tutorial. And remember: type out the examples. You'll thank yourself tomorrow. :)
 
[[File:Scales.png|100px]]
 
So far, the code we've written has been <i>unconditional</i>: no choice is getting made, and the code is always run. Python has another data type called a '''boolean''' that is helpful for writing code that makes decisions. There are two booleans: <code>True</code> and <code>False</code>.
<syntaxhighlight lang="python">
True
 
type(True)
 
False
 
type(False)
</syntaxhighlight>
You can test if Python objects are equal or unequal. The result is a boolean:
<syntaxhighlight lang="python">
0 == 0
 
0 == 1
</syntaxhighlight>
Use <code>==</code> to test for equality. Recall that <code>=</code> is used for <i>assignment</i>.
 
This is an important idea and can be a source of bugs until you get used to it: '''= is assignment, == is comparison'''.
 
Use <code>!=</code> to test for inequality:
<syntaxhighlight lang="python">
"a" != "a"
 
"a" != "A"
</syntaxhighlight>
<code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code> have the same meaning as in math class. The result of these tests is a boolean:
<syntaxhighlight lang="python">
1 > 0
 
2 >= 3
 
-1 < 0
 
.5 <= 1
</syntaxhighlight>
You can check for containment with the <code>in</code> keyword, which also results in a boolean:
<syntaxhighlight lang="python">
"H" in "Hello"


"X" in "Hello"
</syntaxhighlight>
Or check for a lack of containment with <code>not in</code>:
<syntaxhighlight lang="python">
"a" not in "abcde"
"Perl" not in "Python Workshop"
</syntaxhighlight>
==End of Part 2==
==End of Part 2==


Congratulations! You've learned about and practiced executing Python scripts, booleans, conditionals, and making choices with if, elif, and else. This is a huge, huge accomplishment!
Congratulations! You've learned about and practiced executing Python scripts, booleans, conditionals, and making choices with if, elif, and else. This is a huge, huge accomplishment!


[[File:Champagne.png|100px]][[File:Party.png|125px]]
[[File:Party.png|125px]]
 
 
==Common Issues==
 
===I was expecting python to print lots of lines of text when I ran this cell, but it only prints one line!===
Jupyter only outputs the last line of a code chunk unless you explicitly wrap the code in print() statements. If you split your code into multiple chunks or print() the line, it should look like you expect.
 
===There are weird numbers next to my code and I didn't type them!===
Those are line numbers. You can turn them off in the View:Toggle Line Numbers option at the top of the notebook.
Please note that all contributions to CommunityData are considered to be released under the Attribution-Share Alike 3.0 Unported (see CommunityData:Copyrights for details). If you do not want your writing to be edited mercilessly and redistributed at will, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource. Do not submit copyrighted work without permission!

To protect the wiki against automated edit spam, we kindly ask you to solve the following CAPTCHA:

Cancel Editing help (opens in new window)