PyCon handout: Difference between revisions

From OpenHatch wiki
Content added Content deleted
imported>Jesstess
(Created page with "==Math== 100px 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 ...")
 
imported>Jesstess
No edit summary
 
(5 intermediate revisions by the same user not shown)
Line 1: Line 1:
__NOTOC__
==Math==


==Numbers: integers and floats==
[[File:Calculator.png|100px]]


* Integers don't have a decimal place.
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.
* Floats have a decimal place.
* Math mostly works the way it does on a calculator, and you can use parentheses to override the order of operations.


====Math: addition, subtraction, multiplication====
===Addition===


<b>addition</b>: 2 + 2<br />
<pre>
<b>subtraction</b>: 0 - 2<br />
2 + 2
<b>multiplication</b>: 2 * 3<br />
1.5 + 2.25
</pre>

===Subtraction===

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

===Multiplication===

<pre>
2 * 3
</pre>


===Division===
===Division===


Integer division produces an integer:
<pre>
4 / 2
1 / 2
</pre>

Hey now! That last result is probably not what you expected. What's going on here is that integer divison produces an integer. You need a number that knows about the decimal point to get a decimal out of division:


<pre>
<pre>
1.0 / 2
>>> 4 / 2
2
>>> 1 / 2
0
</pre>
</pre>


You need a number that knows about the decimal point to get a decimal out of division:
This means you have to be careful when manipulating fractions. 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. But try that at the Python prompt:


<pre>
<pre>
3/4 + 1/4
>>> 1.0 / 2
0.5
>>> float(1) / 2
0.5
</pre>
</pre>

What do you need to do to get the right answer? Use data types that understand decimals for each of the divisions:

<pre>
3.0/4 + 1.0/4
3.0/4.0 + 1.0/4.0
</pre>

The two previous expressions produce the same result. You only need to make one of the numbers in each fraction have a decimal. When the Python interpreter goes to do the division, it notices that one of the numbers in the fraction cares about decimals and says "that means I have to make the other number care about decimals too".


==Strings==
==Strings==


* Strings are bits of text, and contain characters like numbers, letters, whitespace, and punctuation.
[[File:Letter.png|100px]]
* String are surrounded by quotes.

* Use triple-quotes (""") to create whitespace-preserving multi-line strings.
So far we've seen two data types: <b>integers</b> and <b>floats</b>. Another useful data type is a <b>string</b>, 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:


<pre>
<pre>
"Hello"
>>> print("Hello")
'Hello'
>>> print("Python, I'm your #1 fan!")
"Python, I'm your #1 fan!"
"Python, I'm your #1 fan!"
</pre>

Like with the math data types above, we can use the <code>type</code> function to check the type of strings:

<pre>
type("Hello")
type(1)
type("1")
</pre>
</pre>


Line 78: Line 51:


<pre>
<pre>
"Hello" + "World"
>>> print("Hello" + "World")
'HelloWorld'
</pre>
</pre>


<pre>
<pre>
name = "Jessica"
>>> name = "Jessica"
print "Hello " + name
>>> print("Hello " + name)
'Hello Jessica'
</pre>
</pre>


===Printing===
===String length===


* Use the <code>len</code> function to get the length of a string
You can print strings using <code>print</code>:
* Use the <code>str</code> function to turn something that isn't a string into a string


<pre>
<pre>
h = "Hello"
>>> print(len("Hello"))
4
w = "World"
print h + w
>>> print(len(""))
0
>>> fish = "humuhumunukunukuapuaʻa"
>>> length = str(len(fish))
>>> print(fish + " is a Hawaiian fish whose name is " + length + " characters long.")
</pre>
</pre>


===Quotes===
<pre>
my_string = "Alpha " + "Beta " + "Gamma " + "Delta"
print my_string
</pre>


You can surround a string with either double or single quotes. They mean the same thing:
How about printing different data types together?


<pre>
<pre>
print "Hello" + 1
>>> print('Hello')
'Hello'
>>> print("Hello")
'Hello'
</pre>
</pre>


If your string contains a single quote as an apostrophe, surround the string in double quotes so Python isn't confused by the apostrophe:
Hey now! The output from the previous example was really different and interesting; let's break down exactly what happened:

<code>>>> print "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 is giving us a <b>traceback</b>. 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>TypeError</code>: we tried to do some operation on a data type that isn't supported for that data type.

Python gives us a helpful error message as part of the TypeError:

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

We saw above the we can concatenate strings:


<pre>
<pre>
print "Hello" + "World"
>>> print("I'm a happy camper")
"I'm a happy campter"
</pre>
</pre>


One fun thing about strings in Python is that you can multiply them:
works just fine.

However,


<pre>
<pre>
>>> print("A" * 40)
print "Hello" + 1
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
>>> print "ABC" * 12
ABCABCABCABCABCABCABCABCABCABCABCABC
>>> h = "Happy"
>>> b = "Birthday"
>>> print((h + b) * 10)
HappyBirthdayHappyBirthdayHappyBirthdayHappyBirthdayHappyBirthdayHappyBirthdayHappyBirthdayHappyBirthdayHappyBirthdayHappyBirthday
</pre>
</pre>


==Booleans==
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.


We can convert an integer into a string ourselves, using the <code>str</code> function:
* There are two booleans, <code>True</code> and <code>False</code>.
* Use booleans to make decisions.

====Containment with 'in' and 'not in'====


<pre>
<pre>
print "Hello" + str(1)
>>> "H" in "Hello"
True
>>> "H" not in "Hello"
False
>>> "Perl" not in "Boston Python Workshop"
True
</pre>
</pre>


====Equality====
Like the <code>type</code> function from before, the <code>str</code> function takes 1 argument. In the above example it took the integer 1. <code>str</code> takes a Python object as input and produces a string version of that input as output.


* <code>==</code> tests for equality
===String length===
* <codE>!=</code> tests for inequality

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:
* <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code> have the same meaning as in math class.


<pre>
<pre>
>>> 0 == 0
print len("Hello")
True
print len("")
>>> 0 == 1
fish = "humuhumunukunukuapuaʻa"
False
length = str(len(fish))
>>> "a" != "a"
print fish + " is a Hawaiian fish whose name is " + length + " characters long."
False
>>> "a" != "A"
True
>>> 1 > 0
True
>>> 2 >= 3
False
>>> -1 < 0
True
>>> .5 <= 1
True
</pre>
</pre>


<b>Take note! '=' is for assignment and '==' is for comparison.</b>
===Quotes===


==Flow Control==
We've been using double quotes around our strings, but you can use either double or single quotes:


* Use <code>if</code>, <code>elif</code> and <code>else</code> to make choices.
<pre>
* There is always exactly one <code>if</code>; it is always first and is testing some boolean condition.
print 'Hello'
* You can have zero or many <code>elif</code>; <code>elif</code> also tests some boolean condition.
print "Hello"
* You can have zero or one <code>else</code>; <code>else</code> is a catch-all that goes at the end and does not depend on a boolean condition.
</pre>


====if statements====
Like with spacing above, use whichever quotes make the most sense for you, but be consistent.


We can use these expressions that <i>evaluate</i> to booleans to make decisions and conditionally execute code:
You do have to be careful about using quotes inside of strings:


<pre>
<pre>
>>> if "banana" in "bananarama":
print 'I'm a happy camper'
... print("I miss the 80s.")
...
'I miss the 80s.'
</pre>
</pre>


====more choices: <code>if</code> and <code>else</code>====
This gives us another <b>traceback</b>, for a new kind of error, a <code>SyntaxError</code>. When Python looks at that expression, it sees the string 'I' and then


You can use the <code>else</code> keyword to execute code when the <code>if</code> expression isn't True. For example:
<code>m a happy camper'</code>

which it doesn't understand -- it's not 'valid' Python. Those letters aren't variables (we haven't assigned them to anything), and that trailing quote isn't balanced. So it raises a <code>SyntaxError</code>.

We can use double quotes to avoid this problem:


<pre>
<pre>
>>> sister_age = 15
print "I'm a happy camper"
>>> brother_age = 12
>>> if sister_age > brother_age:
... print("sister is older")
... else:
... print("brother is older")
...
sister is older
</pre>
</pre>


Like with <code>if</code>, the code block under the <code>else</code> statement must be indented so Python knows that it is a part of the <code>else</code> block.
One fun thing about strings in Python is that you can multiply them:


====compound conditionals: <code>and</code> and <code>or</code>====
<pre>
print "A" * 40
print "ABC" * 12
h = "Happy"
b = "Birthday"
print (h + b) * 10
</pre>

==Booleans==

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


* You can check multiple expressions together using the <code>and</code> and <code>or</code> keywords.
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 <b>boolean</b> that is helpful for writing code that makes decisions. There are two booleans: <code>True</code> and <code>False</code>.
* If two expressions are joined by an <code>and</code>, they <b>both</b> have to be True for the overall expression to be True.
* If two expressions are joined by an <code>or</code>, as long as <b>at least one</b> is True, the overall expression is True.


<pre>
<pre>
>>> 1 > 0 and 1 < 2
True
True
>>> 1 < 2 and "x" in "abc"
</pre>
False

>>> "a" in "hello" or "e" in "hello"
<pre>
type(True)
True
>>> 1 <= 0 or "a" not in "abc"
</pre>

<pre>
False
False
</pre>
</pre>


Here are examples of compound conditions in an <code>if</code> statement:
<pre>
type(False)
</pre>

You can test if Python objects are equal or unequal. The result is a boolean:


<pre>
<pre>
>>> temperature = 32
0 == 0
>>> if temperature > 60 and temperature < 75:
... print("It's nice and cozy in here!")
... else:
... print("Too extreme for me.")
...
Too extreme for me.
</pre>
</pre>


<pre>
<pre>
0 == 1
>>> hour = 11
>>> if hour < 7 or hour > 23:
... print("Go away!")
... print("I'm sleeping!")
... else:
... print("Welcome to the cheese shop!")
... print("Can I interest you in some choice gouda?")
...
Welcome to the cheese shop!
Can I interest you in some choice gouda?
</pre>
</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.
Use <code>==</code> to test for equality. Recall that <code>=</code> is used for <i>assignment</i>.


====even more choices: <code>elif</code>====
This is an important idea and can be a source of bugs until you get used to it: <b>= is assignment, == is comparison</b>.


* If you have more than two cases, you can use the <code>elif</code> keyword to check more cases.
Use <code>!=</code> to test for inequality:
* 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 True condition or reaches the default <code>else</code> block.


<pre>
<pre>
>>> sister_age = 15
"a" != "a"
>>> brother_age = 12
>>> if sister_age > brother_age:
... print("sister is older")
... elif sister_age == brother_age:
... print("sister and brother are the same age")
... else:
... print("brother is older")
...
sister is older
</pre>
</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 True.
<pre>
"a" != "A"
</pre>


Here's another example:
<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:


<pre>
<pre>
>>> color = "orange"
1 > 0
>>> if color == "green" or color == "red":
... print("Christmas color!")
... elif color == "black" or color == "orange":
... print("Halloween color!")
... elif color == "pink":
... print("Valentine's Day color!")
...
Halloween color!
</pre>
</pre>


<b>Remember that '=' is for assignment and '==' is for comparison.</b>
<pre>
2 >= 3
</pre>


====In summary: the structure of if/elif/else====
<pre>
-1 < 0
</pre>


Here's a diagram of <code>if/elif/else</code>:
<pre>
.5 <= 1
</pre>


[[File:If-elif-else.png]]
You can check for containment with the <code>in</code> keyword, which also results in a boolean:


==Lists==
<pre>
"H" in "Hello"
</pre>


* Use lists to store data where order matters.
<pre>
* Lists are indexed starting with 0.
"X" in "Hello"
* Lists are denoted by comma-separated elements inside square brackets.
</pre>


====List initialization====
Or check for a lack of containment with <code>not in</code>:


* An empty list is <code>[]</code>
<pre>
* Use the <code>len</code> function to get the length of a list
"a" not in "abcde"
</pre>


<pre>
<pre>
>>> my_list = []
"Perl" not in "Boston Python Workshop"
>>> my_list
[]
>>> your_list = ["a", "b", "c", 1, 2, 3]
>>> your_list
['a', 'b', 'c', 1, 2, 3]
>>> len(your_list)
6
</pre>
</pre>


====Access and adding elements to a list====
==Flow Control==


* Get individual elements from a list with [<index>] syntax.
[[File:Fork.png|100px]]
* Use the <code>in</code> keyword to check if something is in a list.

* Use negative numbers to get element from the end of a list.
====if statements====

We can use these expressions that <i>evaluate</i> to booleans to make decisions and conditionally execute code:


<pre>
<pre>
>>> my_list = ['Amy', 'Alice', 'Adam']
if 6 > 5:
>>> 'Amy' in my_list
print "Six is greater than five!"
True
>>> 'Bob' in my_list
False
>>> len(my_list)
3
>>> my_list[0]
'Amy'
>>> my_list[1]
'Alice'
>>> my_list[-1]
'Adam'
</pre>
</pre>


====Changing elements in a list====
That was our first multi-line piece of code, and the way to enter it at a Python prompt is a little different. First, type the


<code> if 6 > 5:</code>
* Use <code>append</code> to add elements to the end of a list.
* Use the [<index>] syntax to change an element in a list.

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 <b>code block</b>, and so long as we indent our code it should be a part of this code block.

Enter 4 spaces, and then type

<code> print "Six is greater than five!"</code>

Press Enter to end the line, and press Enter again to tell Python you are done with this code block. All together, it will look like this:


<pre>
<pre>
>>> if 6 > 5:
>>> your_list = []
>>> your_list.append("apples")
... print "Six is greater than five!"
>>> your_list[0]
...
'apples'
Six is greater than five!
>>> your_list[0] = "bananas"
>>> your_list
['bananas']
</pre>
</pre>


====Slicing lists====
What is going on here? When Python encounters the <code>if</code> keyword, it <i>evaluates</i> the <i>expression</i> following the keyword and before the colon. If that expression is <b>True</b>, Python executes the code in the indented code block under the <code>if</code> line. If that expression is <b>False</b>, Python skips over the code block.

In this case, because 6 really is greater than 5, Python executes the code block under the if statement, and we see "Six is greater than five!" printed to the screen. Guess what will happen with these other expressions, then type them out and see if your guess was correct:


<pre>
<pre>
>>> her_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
if 0 > 2:
>>> her_list[0]
print "Zero is greater than two!"
'a'
>>> her_list[0:3]
['a', 'b', 'c']
>>> her_list[:3]
['a', 'b', 'c']
>>> her_list[-1]
'h'
>>> her_list[5:]
['f', 'g', 'h']
>>> her_list[:]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
</pre>
</pre>


====Strings are a lot like lists====
<pre>
if "banana" in "bananarama":
print "I miss the 80s."
</pre>

====more choices: <code>if</code> and <code>else</code>====


You can use the <code>else</code> keyword to execute code when the <code>if</code> expression isn't True. Try this:
* You can use the [<index>] and slicing syntax on strings, just like lists.


<pre>
<pre>
>>> my_string = "Hello World"
sister_age = 15
>>> my_string[0]
brother_age = 12
'H'
if sister_age > brother_age:
>>> my_string[:5]
print "sister is older"
'Hello'
else:
>>> my_string[6:]
print "brother is older"
'World'
</pre>
</pre>


== Useful functions related to lists ==
Like with <code>if</code>, the code block under the <code>else</code> statement must be indented so Python knows that it is a part of the <code>else</code> block.


==== sorting lists ====
====compound conditionals: <code>and</code> and <code>or</code>====

You can check multiple expressions together using the <code>and</code> and <code>or</code> keywords. If two expressions are joined by an <code>and</code>, they <b>both</b> have to be True for the overall expression to be True. If two expressions are joined by an <code>or</code>, as long as <b>at least one</b> is True, the overall expression is True.


Use <code>.sort()</code> to sort a list:
Try typing these out and see what you get:


<pre>
<pre>
>>> names = ["Eliza", "Joe", "Henry", "Harriet", "Wanda", "Pat"]
1 > 0 and 1 < 2
>>> names.sort()
>>> names
['Eliza', 'Harriet', 'Henry', 'Joe', 'Pat', 'Wanda']
</pre>
</pre>


==== Getting the maximum and minimum values from a list ====
<pre>
1 < 2 and "x" in "abc"
</pre>


<pre>
<pre>
>>> numbers = [0, 3, 10, -1]
"a" in "hello" or "e" in "hello"
>>> max(numbers)
10
>>> min(numbers)
-1
</pre>
</pre>


== For loops ==
<pre>
1 <= 0 or "a" not in "abc"
</pre>


* Use a <code>for</code> loop to do something for every element in a list.
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.


<pre>
<pre>
>>> names = ["Jessica", "Adam", "Liz"]
temperature = 32
>>> for name in names:
if temperature > 60 and temperature < 75:
print "It's nice and cozy in here!"
... print(name)
...
else:
Jessica
print "Too extreme for me."
Adam
</pre>
Liz</pre>


<pre>
<pre>
>>> names = ["Jessica", "Adam", "Liz"]
hour = 11
>>> for name in names:
if hour < 7 or hour > 23:
... print("Hello " + name)
print "Go away!"
...
print "I'm sleeping!"
Hello Jessica
else:
Hello Adam
print "Welcome to the cheese shop!"
Hello Liz</pre>
print "Can I interest you in some choice gouda?"
</pre>


=== <code>if</code> statements inside <code>for</code> loop ===
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.


====even more choices: <code>elif</code>====
* You can use <code>if</code> statements inside for loops

If you have 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 True condition or reaches the default <code>else</code> block.


<pre>
<pre>
>>> for name in ["Alice", "Bob", "Cassie", "Deb", "Ellen"]:
sister_age = 15
... if name[0] in "AEIOU":
brother_age = 12
... print(name + " starts with a vowel.")
if sister_age > brother_age:
...
print "sister is older"
Alice starts with a vowel.
elif sister_age == brother_age:
Ellen starts with a vowel.</pre>
print "sister and brother are the same age"
else:
print "brother is older"
</pre>


Sometimes you want to start with a new empty list, and only add to that list if some condition is true:
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 True:


<pre>
<pre>
>>> vowel_names = []
color = "orange"
>>> for name in ["Alice", "Bob", "Cassie", "Deb", "Ellen"]:
if color == "green" or color == "red":
... if name[0] in "AEIOU":
print "Christmas color!"
... vowel_names.append(name)
elif color == "black" or color == "orange":
...
print "Halloween color!"
>>> print(vowel_names)
elif color == "pink":
['Alice', 'Ellen']</pre>
print "Valentine's Day color!"
</pre>


=== <code>for</code> loops inside <code>for</code> loops ===
If color had been "purple", that code wouldn't have printed anything.


You can put <code>for</code> loops inside <code>for</code> loops. The indentation dictates which <code>for</code> loop a line is in.
<b>Remember that '=' is for assignment and '==' is for comparison.</b>


<pre>
====In summary: the structure of if/elif/else====
>>> letters = ["a", "b", "c"]
>>> numbers = [1, 2, 3]
>>> for letter in letters:
... for number in numbers:
... print(letter * number)
...
a
aa
aaa
b
bb
bbb
c
cc
ccc</pre>


The order of the <code>for</code> loops matters. Compare the above example with this one:
Here's a diagram of <code>if/elif/else</code>:


<pre>
[[File:If-elif-else.png]]
>>> for number in numbers:

... for letter in letters:
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.
... print(number * letter)
...
a
b
c
aa
bb
cc
aaa
bbb
ccc</pre>

Latest revision as of 13:30, 15 February 2014


Numbers: integers and floats

  • Integers don't have a decimal place.
  • Floats have a decimal place.
  • Math mostly works the way it does on a calculator, and you can use parentheses to override the order of operations.

Math: addition, subtraction, multiplication

addition: 2 + 2
subtraction: 0 - 2
multiplication: 2 * 3

Division

Integer division produces an integer:

>>> 4 / 2
2
>>> 1 / 2
0

You need a number that knows about the decimal point to get a decimal out of division:

>>> 1.0 / 2
0.5
>>> float(1) / 2
0.5

Strings

  • Strings are bits of text, and contain characters like numbers, letters, whitespace, and punctuation.
  • String are surrounded by quotes.
  • Use triple-quotes (""") to create whitespace-preserving multi-line strings.
>>> print("Hello")
'Hello'
>>> print("Python, I'm your #1 fan!")
"Python, I'm your #1 fan!"

String Concatenation

You can smoosh strings together (called "concatenation") using the '+' sign:

>>> print("Hello" + "World")
'HelloWorld'
>>> name = "Jessica"
>>> print("Hello " + name)
'Hello Jessica'

String length

  • Use the len function to get the length of a string
  • Use the str function to turn something that isn't a string into a string
>>> print(len("Hello"))
4
>>> print(len(""))
0
>>> fish = "humuhumunukunukuapuaʻa"
>>> length = str(len(fish))
>>> print(fish + " is a Hawaiian fish whose name is " + length + " characters long.")

Quotes

You can surround a string with either double or single quotes. They mean the same thing:

>>> print('Hello')
'Hello'
>>> print("Hello")
'Hello'

If your string contains a single quote as an apostrophe, surround the string in double quotes so Python isn't confused by the apostrophe:

>>> print("I'm a happy camper")
"I'm a happy campter"

One fun thing about strings in Python is that you can multiply them:

>>> print("A" * 40)
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
>>> print "ABC" * 12
ABCABCABCABCABCABCABCABCABCABCABCABC
>>> h = "Happy"
>>> b = "Birthday"
>>> print((h + b) * 10)
HappyBirthdayHappyBirthdayHappyBirthdayHappyBirthdayHappyBirthdayHappyBirthdayHappyBirthdayHappyBirthdayHappyBirthdayHappyBirthday

Booleans

  • There are two booleans, True and False.
  • Use booleans to make decisions.

Containment with 'in' and 'not in'

>>> "H" in "Hello"
True
>>> "H" not in "Hello"
False
>>> "Perl" not in "Boston Python Workshop"
True

Equality

  • == tests for equality
  • != tests for inequality
  • <, <=, >, and >= have the same meaning as in math class.
>>> 0 == 0
True
>>> 0 == 1
False
>>> "a" != "a"
False
>>> "a" != "A"
True
>>> 1 > 0
True
>>> 2 >= 3
False
>>> -1 < 0
True
>>> .5 <= 1
True

Take note! '=' is for assignment and '==' is for comparison.

Flow Control

  • Use if, elif and else to make choices.
  • There is always exactly one if; it is always first and is testing some boolean condition.
  • You can have zero or many elif; elif also tests some boolean condition.
  • You can have zero or one else; else is a catch-all that goes at the end and does not depend on a boolean condition.

if statements

We can use these expressions that evaluate to booleans to make decisions and conditionally execute code:

>>> if "banana" in "bananarama":
...      print("I miss the 80s.")
... 
'I miss the 80s.'

more choices: if and else

You can use the else keyword to execute code when the if expression isn't True. For example:

>>> sister_age = 15
>>> brother_age = 12
>>> if sister_age > brother_age:
...     print("sister is older")
... else:
...     print("brother is older")
... 
sister is older

Like with if, the code block under the else statement must be indented so Python knows that it is a part of the else block.

compound conditionals: and and or

  • You can check multiple expressions together using the and and or keywords.
  • If two expressions are joined by an and, they both have to be True for the overall expression to be True.
  • If two expressions are joined by an or, as long as at least one is True, the overall expression is True.
>>> 1 > 0 and 1 < 2
True
>>> 1 < 2 and "x" in "abc"
False
>>> "a" in "hello" or "e" in "hello"
True
>>> 1 <= 0 or "a" not in "abc"
False

Here are examples of compound conditions in an if statement:

>>> temperature = 32
>>> if temperature > 60 and temperature < 75:
...     print("It's nice and cozy in here!")
... else:
...     print("Too extreme for me.")
... 
Too extreme for me.
>>> hour = 11
>>> if hour < 7 or hour > 23:
...     print("Go away!")
...     print("I'm sleeping!")
... else:
...     print("Welcome to the cheese shop!")
...     print("Can I interest you in some choice gouda?")
... 
Welcome to the cheese shop!
Can I interest you in some choice gouda?

You can have as many lines of code as you want in if and else blocks; just make sure to indent them so Python knows they are a part of the block.

even more choices: elif

  • If you have more than two cases, you can use the elif keyword to check more cases.
  • You can have as many elif cases as you want; Python will go down the code checking each elif until it finds a True condition or reaches the default else block.
>>> sister_age = 15
>>> brother_age = 12
>>> if sister_age > brother_age:
...     print("sister is older")
... elif sister_age == brother_age:
...     print("sister and brother are the same age")
... else:
...     print("brother is older")
... 
sister is older

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

Here's another example:

>>> color = "orange"
>>> if color == "green" or color == "red":
...   print("Christmas color!")
... elif color == "black" or color == "orange":
...   print("Halloween color!")
... elif color == "pink":
...   print("Valentine's Day color!")
... 
Halloween color!

Remember that '=' is for assignment and '==' is for comparison.

In summary: the structure of if/elif/else

Here's a diagram of if/elif/else:

Lists

  • Use lists to store data where order matters.
  • Lists are indexed starting with 0.
  • Lists are denoted by comma-separated elements inside square brackets.

List initialization

  • An empty list is []
  • Use the len function to get the length of a list
>>> my_list = []
>>> my_list
[]
>>> your_list = ["a", "b", "c", 1, 2, 3]
>>> your_list
['a', 'b', 'c', 1, 2, 3]
>>> len(your_list)
6

Access and adding elements to a list

  • Get individual elements from a list with [<index>] syntax.
  • Use the in keyword to check if something is in a list.
  • Use negative numbers to get element from the end of a list.
>>> my_list = ['Amy', 'Alice', 'Adam']
>>> 'Amy' in my_list
True
>>> 'Bob' in my_list
False
>>> len(my_list)
3
>>> my_list[0]
'Amy'
>>> my_list[1]
'Alice'
>>> my_list[-1]
'Adam'

Changing elements in a list

  • Use append to add elements to the end of a list.
  • Use the [<index>] syntax to change an element in a list.
>>> your_list = []
>>> your_list.append("apples")
>>> your_list[0]
'apples'
>>> your_list[0] = "bananas"
>>> your_list
['bananas']

Slicing lists

>>> her_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> her_list[0]
'a'
>>> her_list[0:3]
['a', 'b', 'c']
>>> her_list[:3]
['a', 'b', 'c']
>>> her_list[-1]
'h'
>>> her_list[5:]
['f', 'g', 'h']
>>> her_list[:]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Strings are a lot like lists

  • You can use the [<index>] and slicing syntax on strings, just like lists.
>>> my_string = "Hello World"
>>> my_string[0]
'H'
>>> my_string[:5]
'Hello'
>>> my_string[6:]
'World'

Useful functions related to lists

sorting lists

Use .sort() to sort a list:

>>> names = ["Eliza", "Joe", "Henry", "Harriet", "Wanda", "Pat"]
>>> names.sort()
>>> names
['Eliza', 'Harriet', 'Henry', 'Joe', 'Pat', 'Wanda']

Getting the maximum and minimum values from a list

>>> numbers = [0, 3, 10, -1]
>>> max(numbers)
10
>>> min(numbers)
-1

For loops

  • Use a for loop to do something for every element in a list.
>>> names = ["Jessica", "Adam", "Liz"]
>>> for name in names:
...     print(name)
...
Jessica
Adam
Liz
>>> names = ["Jessica", "Adam", "Liz"]
>>> for name in names:
...     print("Hello " + name)
...
Hello Jessica
Hello Adam
Hello Liz

if statements inside for loop

  • You can use if statements inside for loops
>>> for name in ["Alice", "Bob", "Cassie", "Deb", "Ellen"]:
...     if name[0] in "AEIOU":
...         print(name + " starts with a vowel.")
... 
Alice starts with a vowel.
Ellen starts with a vowel.

Sometimes you want to start with a new empty list, and only add to that list if some condition is true:

>>> vowel_names = []
>>> for name in ["Alice", "Bob", "Cassie", "Deb", "Ellen"]:
...     if name[0] in "AEIOU":
...         vowel_names.append(name)
... 
>>> print(vowel_names)
['Alice', 'Ellen']

for loops inside for loops

You can put for loops inside for loops. The indentation dictates which for loop a line is in.

>>> letters = ["a", "b", "c"]
>>> numbers = [1, 2, 3]
>>> for letter in letters:
...     for number in numbers:
...         print(letter * number)
...
a
aa
aaa
b
bb
bbb
c
cc
ccc

The order of the for loops matters. Compare the above example with this one:

>>> for number in numbers:
...     for letter in letters:
...         print(number * letter)
...
a
b
c
aa
bb
cc
aaa
bbb
ccc