Closely following Automate the boring stuff with Python
Financial Software Developer at Bloomberg
Financial Software Developer at Bloomberg
News Automation Engineer at Bloomberg
System Reliability Engineer at Bloomberg
Closely following Automate the boring stuff with Python
Let's play with repl.it:
>>> 2 + 2
4
Do you know any other operators?
There are plenty of operators available:
Operator | Operation | Example |
---|---|---|
+ | Addition | 1 + 7 evaluates to 8 |
- | Subtraction | 80 - 12 evaluates to 68 |
* | Multiplication | 2 * 3 evaluates to 6 |
/ | Division | 15 / 4 evaluates to 3.75 |
** | Exponent | 2 ** 3 evaluates to 8 |
% | Modulus/Remainder | 22 % 8 evaluates to 6 |
// | Integer Division/Floored Quotient | 22 // 8 evaluates to 2 |
>>> 2 ** 8
256
>>> (5 - 1) * ((7 + 1) / (3 - 1))
16.0
>>> 42 + 5 + * 2
File "python", line 1
42 + 5 + * 2
^
SyntaxError: invalid syntax
>>> 5 +
File "python", line 1
5 +
^
SyntaxError: invalid syntax
Data Type | Examples |
---|---|
Integer | -2, -1, 0, 1, 2, 3, 4, 5 |
Floating Point Numbers (Float) | -1.25, 1.0, 17.999, 20.1 |
Strings | 'a', 'hello world', '20 cars', ' ' |
>>> 'Hello world!
SyntaxError: EOL while scanning string literal
What went wrong here?
The behaviour of operator changes depending on the data types:
>>> 'Alice' + 'Bob'
'AliceBob'
This is called string concatenation
>>> 'Alice' + 42
Traceback (most recent call last):
File "python", line 1
'Alice' + 42
TypeError: Can't convert 'int' object to str implicitly
Python doesn't understand this
>>> 'Alice' * 5
'AliceAliceAliceAliceAlice'
Makes sense again
variableis like a box in the computer's memory where you can store a single value. If you save a value into a variable you can reuse it later on
>>> spam = 42
>>> spam
42
initialized:
>>> spam = 40
>>> spam
40
You can then use that variable in expressions:
>>> eggs = 2
>>> spam + eggs
42
>>> spam + eggs + spam
82
If you want to assign a new value to a variable. This is called overwriting the variable:
>>> spam = spam + 2
>>> spam
42
>>> spam = 'Hello'
>>> spam
'Hello'
>>> spam = 'Goodbye'
>>> spam
'Goodbye'
>>> password_to_pc = 'top secret' # valid
>>> _password = 'test' # valid
>>> myPassword = 'my pets name' # valid
>>> 4password # cannot start with a number
>>> password-to-pc # cannot use hyphens
>>> password to pc # no spaces
>>> bank_account_nr = 12345 # snake case
>>> bankAccountNr = 12345 # camel case
Pick one and stick with it
(Python convention is snake case)
# This program says hello and asks for my name.
print('Hello world!')
print('What is your name?') # ask for their name
my_name = input() # raw_input if you're in python2
print('It is good to meet you, ' + my_name)
print('The length of your name is:')
print(len(my_name))
print('What is your age?') # ask for their age
my_age = input()
print('You will be ' + str(int(my_age) + 1) + ' in a year.')
Make sure you save it!
# This program says hello and asks for my name.
Text following a hash mark is a comment
print('Hello world!')
print('What is your name?') # ask for their name
The print()
function prints everything inside the parenthesis on the screen.
We say that python is callingthe
print()
function with a string
value passed to the function. A value passed to a function is called an
argument
print
would refer to a variable.
my_name = input()
input waits for the user's input and saves it into my_name
as a string
print('It is good to meet you, ' + my_name)
If 'Kathrin' was stored in my_name
then this expression would print
"It is good to meet you, Kathrin"
print('The length of your name is:')
print(len(my_name))
len()
functions evaluates the length of a string. Try it out:
>>> len('hello')
5
>>> len('I really like learning Python')
29
>>> len('')
0
len()
function is then passed to the print()
function.
The print()
function can take integers and string values but try mixing the two:
>>> print('I am ' + 29 + ' years old.')
Traceback (most recent call last):
File "python", line 1
print('I am ' + 29 + ' years old.')
TypeError: Can't convert 'int' object to str implicitly
>>> str(29)
'29'
>>> print('I am ' + str(29) + ' years old.')
>>> int('-99')
-99
>>> int(1.25)
1
>>> int(1.99)
1
>>> float('3.14')
3.14
>>> float(10)
10.0
print('What is your age?') # ask for their age
my_age = input()
print('You will be ' + str(int(my_age) + 1) + ' in a year.')
int(my_age) + 1
str(int(my_age) + 1)
>>> 42 == 37
False
>>> 42 == '42'
False
>>> 42 == 42.0
True
>>> 42.0 == 0042.000
True
>>> my_first_bool = True
>>> spam = True
>>> spam
>>> True
Some more questions to try in your terminal:
true
with a lower case t?
>>> true
True
or
False
as the name of a variable?
>>> True = 2 + 2
False == False
? Why?
>>> False == False
This is called comparison operatorsand we'll cover that next!
Operator | Meaning |
---|---|
== | Equal to |
!= | Not equal to |
< | Less than |
> | More than |
<= | Less than or equal to |
>= | More than or equal to |
>>> 42 == 42
>>> 42 == 99
>>> 2 != 3
>>> 2 != 2
>>> 'hello' == 'hello'
>>> 'hello' == 'Hello'
>>> 'dog' != 'cat'
>>> True != False
>>> 42 == 42.0
>>> 42 == '42'
>>> 42 < 100
>>> 42 > 100
>>> 42 < 42
>>> my_number = 42
>>> my_number <= 42
>>> my_age = 29
>>> my_age >= 10
Click here for another exercise
And find even more questions here
and
or
not
and
operator
>>> (5 > 2) and (5 < 10)
>>> True
>>> (5 == 2) and (5 < 10)
>>> False
Example: You need to be older than 20 and younger than 30.
>>> age = 27
>>> (age > 20) and (age < 30)
>>> True
or
operator
>>> (27 > 20) or (5 < 1)
>>> True
>>> (5 == 2) or (5 < 1)
>>> False
Example: To watch Netflix on your phone you need to be connected to Wifi OR have a mobile data connection.
>>> wifi_connection = True
>>> mobile_connection = False
>>> wifi_connection or mobile_connection
>>> True
not
operatorand
and or
the not
operator only takes one Boolean
Evaluates to the opposite of the Boolean value
>>> not True
>>> False
>>> not not False
>>> False
Example: If you are not in debt you can get a credit card
>>> in_debt = True # owes money to someone
>>> not in_debt
>>> False # can not get a credit card
>>> (4 < 5) and (5 < 6)
>>> (4 < 5) and (9 < 6)
>>> (1 == 2) or (2 == 2)
>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
Click here for another exercise
*
'hello'
-88.8
-
/
+
5
'spam'
spam
>>> bacon = 20
>>> bacon + 1
print('I have eaten' + 99 + 'burritos')
(5 > 4) and (3 == 5)
not (5 > 4)
(5 > 4) or (3 == 5)
not ((5 > 4) or (3 == 5))
(True and True) and (True == False)
(not False) or (not True)
Closely following Automate the boring stuff with Python
Flow control.
True
or False
.
A flow control statement decides what to do based on whether its condition is True or False.
Blocks. You can tell when a block begins and Ends by indentation.
if name == 'Alice':
print('Hi, Alice')
if
keywordif clause)
if name == 'Alice':
print('Hi, Alice')
if name == 'Alice':
print('Hi, Alice')
else:
print('Hello, stranger')
else
keywordelse clause)
if name == 'Alice':
print('Hi, Alice')
else:
print('Hello, stranger')
if name == 'Alice':
print('Hi, Alice')
elif age < 12:
print('You are not Alice, kiddo')
elif
keywordelif clause)
if name == 'Alice':
print('Hi, Alice')
elif age < 12:
print('You are not Alice, kiddo')
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif age > 100:
print('You are not Alice, grannie.')
The order of the statements matters. Can you see why?
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 100:
print('You are not Alice, grannie.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 100:
print('You are not Alice, grannie.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
else:
print('I dont know who you are, but certainly not Alice')
>>> "Do you have wifi?" yes
>>> "Do you have mobile data?" yes
>>> "You can access the internet through wifi"
>>> "Do you have wifi?" yes
>>> "Do you have mobile data?" no
>>> "You can access the internet through wifi"
>>> "Do you have wifi?" no
>>> "Do you have mobile data?" yes
>>> "You can access the internet through mobile data"
>>> "Do you have wifi?" no
>>> "Do you have mobile data?" no
>>> "I am sorry, you cannot access the internet"
Think about how you can handle different cases of a user writing "yes" (yes/Yes/YES/Y, etc)
spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
while
keywordwhile clause)
name = ''
while name != 'your name':
print('Please type your name.')
name = input()
print('Thank you!')
Try it out! How can you reach the 'Thank you'? Why?
while True:
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')
num = 0
while num < 10:
num = num + 1
if num % 2 == 0:
# number is even
continue
print(num)
for i in range(5):
print(i)
In Python, a for loop consists of the following:
for
keywordin
keyword range()
range(start, stop, step)
Range is a function that returns a list like sequence of values up to a stop value.
The list returned excludes the stop value.
Try it out! Replace the range function in the loop on the previous slide with the following:
range(0,5)
range(3,10)
range(10,20,2)
for i in range(5):
print(i)
i = 0
while i < 5:
print(i)
i = i + 1
In this case, the for loop is neater and easier to understand. Choose the loop depending on the situation.
while True:
print('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello, Joe. What is the password? (It is a fish.)')
password = input()
if password == 'swordfish':
break
print('Access granted.')
Closely following Automate the boring stuff with Python
print(), input() and len()
.
These are all built in functions but you can also write your own. Functions are just a named container for a block of code.
def hello():
print('Howdy!')
print('Howdy!!!')
print('Hello there.')
return
hello()
hello()
hello()
Let's have a closer look:
Function definition:
def hello():
print('Howdy!')
print('Howdy!!!')
print('Hello there.')
return
def
defines a function called hello.
The bodyis executed when we call this function, not when we define it.
Function call:
hello()
hello()
hello()
print('Howdy!')
print('Howdy!!!')
print('Hello there.')
print('Howdy!')
print('Howdy!!!')
print('Hello there.')
print('Howdy!')
print('Howdy!!!')
print('Hello there.')
print()
we passed in values, so called arguments. Can we pass an argument to our function hello?
# Function definitions
def hello(name):
print('Hello ' + name)
return
# Code starts here
hello('Alice')
hello('Bob')
>>> hello()
>>> File "python", line 5
TypeError: hello() missing 1 required positional argument: 'name'
# Function definitions
def hello(name, age):
print('Hello ' + name)
print('You are ' + str(age) + ' years old')
return
# Code starts here
hello('Alice', 17)
hello('Bob', 45)
# Function definitions
def hello(name, age):
print('Hello ' + name)
print('You are ' + str(age) + ' years old')
return
# Code starts here
user_name = input("What's your name?")
user_age = int(input("What's your age?"))
hello(user_name, user_age)
hello('Bob', 45)
print_sum(number1, number2)
that takes two numbers as arguments and prints out the sum?
Can you call it with different arguments to test it?
def print_sum(number1, number2):
# Your code goes here
This is how the call and output would look like:
print_sum(3, 7)
>>> "The sum of 3 and 7 is 10!"
Bonus points: Can you ask the user to input the number? (Hint: The input should be outside of the function and then passed to it. For a similar example check here)
count
that takes a number as an argument and then counts up to this number?
Can you call it with different arguments to test it?
def count(number):
# Your code goes here
This is how the call and output would look like:
count(3)
>>> 1
>>> 2
>>> 3
>>> GO!
Hint: You can use a for-loop for this
Bonus points: Can you ask the user to input the number? Can you also ask the user if he/she wants to count up or down and act accordingly? (Hint: Ask the user and then pass it to the function you wrote before)
len()
function with 'Hello' it will evaluate to the value 5.
We call this a return value. A function can do something and then either leave it at and return nothing to the user or it can return something.
# Function definition
def get_answer(number):
if number == 1:
return 'It is certain'
elif number == 2:
return 'It is decidedly so'
else:
return 'I dont know the answer to this'
# Code starts here
fortune = get_answer(5)
print(fortune)
fortune = get_answer(3)
print(fortune)
we can also chain this call:
print(get_answer(3))
print('Tell me a number: ')
number = int(input())
fortune = get_answer(number)
print(fortune)
Remember that we need to create an int out of the input string!
This way someone else could write the function get_answer and we can just use it!
# Function definitions:
def get_max(number1, number2):
# Your code goes here..
# Code execution starts here
maximum = get_max(3,7)
print(maximum) # This should print 7
Hint: You will need if statements.
Hint 2: This is just a practice function. Python has a built-in function max() that does exactly that!
Another review exercise is here!
import random
random_number = random.randint(1, 10)
We call random a module.
from random import randint
random_number = randint(1, 10)
This way you don't have to type random.randint every time.
These modules and functions are all very well documented, for example: https://docs.python.org/3.6/library/random.html
import datetime
print(datetime.datetime.today())
or
from datetime import datetime
print(datetime.today())
# Your import statements go here:
# Function definitions:
def get_birth_year(age):
# Your code goes here. Do some magic and return birth year:
# Code execution starts here
age = # Ask the user for his age
birth_year = # Call your function with age
print('You were born in ' + str(birth_year))
Hint: You will need to find out how you can get the current year
I am thinking of a number between 1 and 20.
Take a guess.
10
Your guess is too low.
Take a guess.
15
Your guess is too low.
Take a guess.
17
Your guess is too high.
Take a guess.
16
Good job! You guessed my number in 4 guesses!
import random
# The computer generates a random number
secret_number = random.randint(1,20)
print('I am thinking of a number between 1 and 20')
# Ask the player to guess maximum 6 times.
total_guesses_taken = 0
while total_guesses_taken < 6:
total_guesses_taken = total_guesses_taken + 1
print('Take a guess.')
guess = int(input())
if guess < secret_number:
print('Your guess is too low.')
elif guess > secret_number:
print('Your guess is too high.')
else:
break # This is the correct guess, we can exit the while loop now
if guess == secret_number:
print('Good job! You guessed my number in ' + str(total_guesses_taken) + ' guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secret_number))
bacon()
in a module named spam
, how would you call it after import spam?
collatz()
that has one parameter named number. If number is even, then collatz()
should print number // 2 and return this value. If number is odd, then collatz()
should print and return 3 * number + 1.
def collatz(number):
# Your code
collatz()
on that number until the function returns the value 1.
number % 2 == 0
(If number % 2 == 1
the number is odd).
Maybe you can adapt the following code to help you?
if number % 2 == 0:
print("This number is even")
else:
print("This number is odd")
Enter number: 3
10
5
16
8
4
2
1
Closely following Automate the boring stuff with Python
None
which means no value/absent value.
Just like True
and False
this must be capitalized: None
return None
to the end of every function where nothing else is specified.
return
without a value will also mean None
def hello():
print("test")
... is the same as ...
def hello():
print("test")
return None
... is the same as ...
def hello():
print("test")
return
print("test", "bla", "something else", "etc")
Does that mean you can't specify anything else?
print('Hello')
print('World')
will produce:
>>> Hello
>>> World
print('Hello', end='')
print('World')
>>> HelloWorld
end
is called a keyword argument because you have to call it by it's name
print('cats', 'dogs', 'mice')
>>> cats dogs mice
Python automatically puts a single space between. If you want to change that behaviour, you can change the sep
argument of the print function:
print('cats', 'dogs', 'mice', sep=',')
>>> cats,dogs,mice
>>> shirts|trousers|blouses|shoes
Ask the user to input a number. Can you print all the numbers from 1 to the user's number like that?
>>> 1|2|3|4|5
local scope. Variables that are assigned outside all functions are said to exist in the
global scope.
# Function Definitions
def spam():
eggs = 31337
# Execution starts here
spam()
print(eggs)
eggs variable is only known in the local scope of spam!
Traceback (most recent call last):
File "C:/test3784.py", line 4
print(eggs)
NameError: name 'eggs' is not defined
# Function Definitions
def spam():
print(eggs)
# Execution starts here
eggs = 42
spam()
Will print out:
>>> 42
# Function Definitions
def spam():
eggs = 19
print(eggs)
# Execution starts here
eggs = 42
spam()
What will be printed? Why?
Closely following Automate the boring stuff with Python
>>> [1, 2, 5]
[1, 2, 5]
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam
['cat', 'bat', 'rat', 'elephant']
spam is assigned the whole list!
List Indexes
You can access the elements in a list with indexes:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0]
'cat'
>>> spam[1]
'bat'
>>> spam[2]
'rat'
>>> ['cat', 'bat', 'rat', 'elephant'][3]
'elephant'
The first index is always 0
IndexError
if you use an index that exceeds the number of values in your list:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[10000]
Traceback (most recent call last):
File "python", line 1
spam[10000]
IndexError: list index out of range
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1.0]
Traceback (most recent call last):
File "python", line 1
spam[1.0]
TypeError: list indices must be integers, not float
>>> spam = [['cat', 'bat'], [10, 20, 30, 40, 50]]
>>> spam[0]
['cat', 'bat']
>>> spam[0][1]
'bat'
>>> spam[1][4]
50
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1]
'elephant'
>>> spam[-3]
'bat'
>>> 'The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.'
'The elephant is afraid of the bat.'
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0:4]
['cat', 'bat', 'rat', 'elephant']
>>> spam[1:3]
['bat', 'rat']
>>> spam[0:-1]
['cat', 'bat', 'rat']
In a slice, the first integer is the index where the slice starts.
The second integer is the index where the slice ends (not inclusive!).
A slice evaluates to a new list value.
>>> spam[:2] # Beginning to index 2
['cat', 'bat']
>>> spam[1:] # Index 1 to end
['bat', 'rat', 'elephant']
>>> spam[:] # everything
['cat', 'bat', 'rat', 'elephant']
>>> spam = ['cat', 'dog', 'moose']
>>> len(spam)
3
spam = 42
. But you can assign an index in a list:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1] = 'aardvark'
>>> spam
['cat', 'aardvark', 'rat', 'elephant']
>>> spam[2] = spam[1]
>>> spam
['cat', 'aardvark', 'aardvark', 'elephant']
>>> spam[-1] = 12345
>>> spam
['cat', 'aardvark', 'aardvark', 12345]
append
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.append('dog')
>>> [1, 2, 3] + ['A', 'B', 'C']
[1, 2, 3, 'A', 'B', 'C']
>>> ['X', 'Y', 'Z'] * 3
['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
>>> spam = [1, 2, 3]
>>> spam = spam + ['A', 'B', 'C']
>>> spam
[1, 2, 3, 'A', 'B', 'C']
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat']
There is another way here too (to remove by element, not by index)!
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('cat')
spam = [2, 4, 6, 8, 10]
1. How would you assign the value 'hello' as the third value in spam?
2. Can you append ['cat', 'dog', 'bird'] to spam?
3. Can you delete the last element? Can you delete the first?
4. Can you delete the element 'dog'?
cat_name1 = 'Zophie'
cat_name2 = 'Pooka'
cat_name3 = 'Simon'
cat_name4 = 'Lady Macbeth'
cat_name5 = 'Fat-tail'
cat_name6 = 'Miss Cleo'
print('Enter the name of cat 1:')
cat_name1 = input()
print('Enter the name of cat 2:')
cat_name2 = input()
print('Enter the name of cat 3:')
cat_name3 = input()
print('Enter the name of cat 4:')
cat_name4 = input()
print('Enter the name of cat 5:')
cat_name5 = input()
print('The cat names are:')
print(cat_name1 + ' ' + cat_name2 + ' ' + cat_name3 + ' ' + cat_name4 + ' ' +
cat_name5)
This is very repetitive.. and not extensible (What if you have 7 cats?)
cat_names = []
while True:
print('Enter the name of cat ' + str(len(cat_names) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
cat_names = cat_names + [name] # list concatenation
print('The cat names are:')
for name in cat_names:
print(' ' + name)
Let's try running this program!
for i in range(4):
print(i)
This is because range
returns a list-like value
>>> supplies = ['pens', 'staplers', 'flame-throwers', 'binders']
>>> for supply in supplies
print('The supply is: ' + supply)
The supply is: pens
The supply is: staplers
The supply is: flame-throwers
The supply is: binders
numbers = [1, 3, 5, 10, 6]
# Your code goes here
print(sum) # This should print 25
Bonus: Can you make it a function that takes a list as input?
Bonus2: Can you ask the user for numbers like we asked for cat names?
in
and not in
expressions.
>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']
True
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> 'cat' in spam
False
>>> 'howdy' not in spam
False
>>> 'cat' not in spam
True
my_pets = ['Zophie', 'Pooka', 'Fat-tail']
print('Enter a pet name:')
name = input()
if name not in my_pets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')
The output might look something like this:
Enter a pet name:
Footfoot
I do not have a pet named Footfoot
import random
messages = ['It is certain',
'It is decidedly so',
'Yes definitely',
'Reply hazy try again',
'Ask again later',
'Concentrate and ask again',
'My reply is no',
'Outlook not so good',
'Very doubtful']
random_index = random.randint(0, len(messages) - 1)
print(messages[random_index])
Can you explain why we need the -1?
>>> cat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
>>> cat['size']
'fat'
>>> 'Cat has a ' + cat['disposition'] + ' disposition'
'Cat has a loud disposition'
For dictionaries, indexes are known are keys. Each element is a key-value pair.
>>> cat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
>>> tab = {'disposition': 'loud', 'size': 'fat', 'color': 'gray'}
>>> cat == tab
True
Since there's no ordering, slicing a dictionary doesn't make sense.
KeyError
if a key does not exist in your dictionary:
>>> cat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
>>> cat['age']
Traceback (most recent call last):
File "python", line 1
KeyError: 'age'
>>> equity = {
'ticker': 'AAPL',
'price': 104.6,
'tradeable': True,
'exchange': 'US'
}
>>> equity['ticker']
'AAPL'
>>> ages = {'Tom': 23, 'Gabriel': 27, 'Kathrin': 25}
>>> ages['Tom']
23
>>> ages['Kathrin']
25
>>> ages = {'Tom': 23, 'Gabriel': 27, 'Kathrin': 25}
>>> ages['Tom']
23
>>> ages['Tom'] = ages['Tom'] + 1
>>> ages['Tom']
24
>>> ages = {'Tom': 23, 'Gabriel': 27, 'Kathrin': 25}
>>> ages['Naomi']
Traceback (most recent call last):
File "python", line 1
KeyError: 'Naomi'
>>> ages['Naomi'] = 26
>>> ages
{'Tom': 23, 'Gabriel': 27, 'Kathrin': 25, 'Naomi': 26}
>>> ages = {'Tom': 23, 'Gabriel': 27, 'Kathrin': 25}
>>> del ages['Kathrin']
>>> ages
{'Tom': 23, 'Gabriel': 27}
>>> ages = {'Tom': 23, 'Gabriel': 27, 'Kathrin': 25}
>>> 'Naomi' in ages
False
>>> 'Kathrin' in ages
True
if
and else
to do some interesting things
if 'Gabriel' in ages:
print('Gabriel is ' + str(ages['Gabriel']) + ' years old')
else:
print("We do not have Gabriel's age")
>>> ages = {'Tom': 23, 'Gabriel': 27, 'Kathrin': 25}
>>> for age in ages.values():
... print(age)
23
27
25
>>> ages = {'Tom': 23, 'Gabriel': 27, 'Kathrin': 25}
>>> for name in ages.keys():
... print(name)
Tom
Gabriel
Kathrin
>>> ages = {'Tom': 23, 'Gabriel': 27, 'Kathrin': 25}
>>> for item in ages.items():
... print(item)
... print(item[0] + ' -> ' + str(item[1]))
('Tom', 23)
'Tom -> 23'
('Gabriel', 27)
'Gabriel -> 27'
('Kathrin', 25)
'Kathrin -> 25'
Using items()
will give you the key-value pairs
spam = ['a', 'b', 'c', 'd']
1. What does spam[int(int('3' * 2) // 11)]
evaluate to?spam[-1] evaluate to?
spam[:2] evaluate to?
append()
, remove()
and index()
bacon = [3.14, 'cat', 11, 'cat', True]
1. What does bacon.index('cat')
evaluate to?bacon.remove('cat')
do? What does bacon look like now?
bacon.append(99)
do? What does bacon look like now?
spam['foo']
if spam = {'bar': 100}?
spam
is a dictionary'cat' in spam
and 'cat' in spam.keys()
?'cat' in spam
and 'cat' in spam.values()
?spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item.
For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'.
But your function should be able to work with any list value passed to it.
{'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
means the player has 1 rope, 6 torches, 42 gold coins, and so on.
display_inventory()
that would take any possible “inventory” (dictionary) and display it like the following:
Inventory:
12 arrow
42 gold coin
1 rope
6 torch
1 dagger
Total number of items: 63
treasure = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
Write a function named add_to_inventory(inventory, added_items)
, where the inventory parameter is a dictionary
representing the player’s inventory (like in the previous project) and the added_items parameter is a list like treasure.
The add_to_inventory() function should return a dictionary that represents the updated inventory.
Note that the added_items list can contain multiples of the same item. Your code could look something like this:
#Function definitions
def display_inventory(inventory):
# Code you wrote before
def add_to_inventory(inventory, added_items):
# your code goes here
# Code execution starts here
inv = {'gold coin': 42, 'rope': 1}
treasure = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = add_to_inventory(inv, treasure)
display_inventory(inv)
And the output could look something like this...
Inventory:
45 gold coin
1 rope
1 ruby
1 dagger
Total number of items: 48
Closely following Automate the boring stuff with Python
# Needed imports: This is the python excel module
import openpyxl
# Open our excel workbook from a file path.
wb = openpyxl.load_workbook('example.xlsx')
type(wb)
type(wb)
simply lets you inspect the type of the object in that variable. You don't need it to proceed and it's advisable to remove it in order to reduce the spam output.
Out[3]: openpyxl.workbook.workbook.Workbook
wb.worksheets
Note that this is not a function call, that's why there are no '()'
Out [7]: [<Worksheet "Sheet1">, <Worksheet "Sheet2">, <Worksheet "Sheet3">]
You can now assign a variable to the sheet we want to work with. You can also inspect that
# Access the first sheet of the workbook
sheet = wb.worksheets[0]
sheet.title
Out [7]: 'Sheet1'
sheet['A1'].value
Out[9]: datetime.datetime(2015, 4, 5, 13, 34, 2)
c = sheet['B1']
print('Row ' + str(c.row) + ', Column ' + c.column + ' is ' + c.value)
print('Cell ' + c.coordinate + ' is ' + c.value)
Out [11]: Row 1, Column B is Apples
Cell B1 is Apples
As you may have noticed, c is a Cell object. If you want the value you will need to access it using .value
You can access many properties on a cell, such as row, column, coordinate and value
sheet.cell(row=1, column=2)
sheet.cell(row=1, column=2).value
This way you can iterate over cells:
for i in range(1,8,2):
print(i, sheet.cell(row=i, column=2).value)
1 Apples
3 Pears
5 Apples
7 Strawberries
sheet.max_row
sheet.max_column
OUT[14]: 7
3
for cells in sheet.iter_rows(min_col=2, max_col=2):
print(cells[0].value)
Out[12]: Apples
Cherries
Pears
Oranges
Apples
Bananas
Strawberries
iter_rows returns a list of rows with cells from min_col to max_col!
In [1]: import openpyxl
In [2]: wb = openpyxl.load_workbook('dataset.xlsx')
In [3]: sheet = wb.worksheets[0]
down_nodes = {}
The result will look something like this:
{
'ATS1-1A-NODE-SW1' : 1,
'ATS1-1A-NODE-SW2' : 3,
....
}
for row_number in range(2, sheet.max_row + 1):
# Retrieve switch name from the cell in column 1
switch_name = sheet.cell(row=row_number, column=1).value
# If we see switch_name for the first time we add it
if switch_name not in down_nodes:
down_nodes[switch_name] = 0
# Retrieve status from the cell in column 6
status = sheet.cell(row=row_number, column=6).value
# If the status is "down" we want to increase the number:
if status == 'down':
down_nodes[switch_name] = down_nodes[switch_name] + 1
down_nodes
{
'ATS1-1A-NODE-SW1': 1,
'ATS1-1A-NODE-SW2': 4,
'ATS2-1A-NODE-SW1': 6,
'ATSS-7A-CORP-SW1': 24,
'ATSS-7A-CORP-SW2': 11
}
Switch Name | # Down |
---|---|
ATS1-1A-NODE-SW1 | 1 |
ATS1-1A-NODE-SW2 | 4 |
# Creating a new file, make it writeable
result_file = open('results.txt', 'w')
# Empty the file (don't do this if you just append to a file)
result_file.truncate()
# Iterate over our dictionary and write to file
for item in down_nodes.items():
result_file.write(item[0] + ': ' + str(item[1]) + '\n')
# Close the file
result_file.close()
And you have successfully created a text file using Python!! :)
# There is no second sheet yet, so we can create it:
results_sheet = wb.create_sheet('Results')
# Create Header row
results_sheet.cell(row=1, column=1).value = 'Switch'
results_sheet.cell(row=1, column=2).value = '# Down'
# Write to the sheet (start from row 2)
row = 2
for item in down_nodes.items():
results_sheet.cell(row=row, column=1).value = item[0]
results_sheet.cell(row=row, column=2).value = item[1]
row = row + 1
# Now you just need to save the sheet (choose the same name or another one)
# We recommend to keep the original "clean" and save to a new name.
wb.save('dataset_results.xlsx')
# First we need to define/create our fill-style
fill_style_green = openpyxl.styles.PatternFill("solid", fgColor=openpyxl.styles.colors.GREEN)
# Now we can iterate over all the rows and assign
# the style to them
for row in sheet.rows:
duplex_cell = row[2]
if duplex_cell.value == 'unknown':
duplex_cell.fill = fill_style_green
# Don't forget to save!
wb.save('dataset_results.xlsx')
import pandas as pd
import numpy as np
Dataframes can be created in many different ways, here we create using a dict.
dict = {'employee': ['Bob', 'Jake', 'Lisa', 'Sue'],
'group': ['Accounting', 'Engineering', 'Engineering', 'HR']}
dataframe = pd.DataFrame(dict)
print(dataframe)
Extract a column
roles = dataframe['group']
Extract some data
dataframe.loc[dataframe['employee']=='Lisa', 'group']
df1 = pd.DataFrame({'employee': ['Bob', 'Jake', 'Lisa', 'Sue'],
'group': ['Accounting', 'Engineering', 'Engineering', 'HR']})
df2 = pd.DataFrame({'employee': ['Lisa', 'Bob', 'Jake', 'Sue'],
'hire_date': [2004, 2008, 2012, 2014]})
display(df1, df2)
df3 = pd.merge(df1, df2)
display(df3)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Read the csv
data = pd.read_csv("price_data.csv")
Plot
data.plot()