PyCon handout
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
andFalse
. - 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
andelse
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
andor
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 eachelif
until it finds a True condition or reaches the defaultelse
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'
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