Functions and Conditionals
In this section, you learned to:
Define a function:
1. def cube_volume(a):
2. return a * a * a
Write a conditional block:
1. message = "hello there"
2.
3. if "hello" in message:
4. print("hi")
5. else:
6. print("I don't understand")
Write a conditional block of multiple
conditions:
1. message = "hello there"
2.
3. if "hello" in message:
4. print("hi")
5. elif "hi" in message:
6. print("hi")
7. elif "hey" in message:
8. print("hi")
9. else:
10. print("I don't understand")
Use the and operator to check if both
conditions are True at the same
time:
1. x = 1
2. y = 1
3.
4. if x == 1 and y==1:
5. print("Yes")
6. else:
7. print("No")
Output is Yes since both x and y are 1.
Use the or operator to check if at least one
condition is True:
1. x = 1
2. y = 2
3.
4. if x == 1 or y==2:
5. print("Yes")
6. else:
7. print("No")
Output is Yes since x is 1.
Check if a value is of a particular type with:
1. isinstance("abc", str)
2. isinstance([1, 2, 3], list)
or
1. type("abc") == str
2. type([1, 2, 3]) == lst
Processing User Input
In this section, you learned that:
A Python program can get user input via
the input function:
The input function halts the execution of
the program and gets text input from the user:
1. name = input("Enter your name: ")
The input function converts any input to a string, but you
can convert it back to int or float:
1. experience_months = input("Enter your
experience in months: ")
2. experience_years = int(experience_months) / 12
You can format strings with (works both on Python 2 and
3):
1. name = "Sim"
2. experience_years = 1.5
3. print("Hi %s, you have %s years of experience."
% (name, experience_years))
Output: Hi Sim, you have 1.5 years of experience.
You can also format strings with:
1. name = "Sim"
2. experience_years = 1.5
3. print("Hi {}, you have {} years of
experience".format(name, experience_years))
Output: Hi Sim, you have 1.5 years of experience.
For Loop Over a Function
Note that using loops, you can call any function multiple times,
even your own functions. Let's suppose we defined this
function:
1. def celsius_to_kelvin(cels):
2. return cels + 273.15
That is a function that gets a number as input, adds 273.15 to it
and returns the result. A for loop allows us to execute that
function over a list of numbers:
1. monday_temperatures = [9.1, 8.8, -270.15]
2.
3. for temperature in monday_temperatures:
4. print(celsius_to_kelvin(temperature))
The output of that would be:
282.25
281.95
3.0
So, in the first iteration celsius_to_kelvin(9.1) was
executed, in the second celsius_to_kelvin(8.8) and in the
third celsius_to_kelvin(-270.15) .
That's just something to keep in mind.
Dictionary Loop and String
Formatting
You can combine a dictionary for loop with string formatting to
create text containing information from the dictionary:
1. phone_numbers = {"John Smith": "+37682929928",
"Marry Simpons": "+423998200919"}
2.
3. for pair in phone_numbers.items():
4. print("{} has as phone number
{}".format(pair[0], pair[1]))
Another (better) way to do it::
1. phone_numbers = {"John Smith": "+37682929928",
"Marry Simpons": "+423998200919"}
2.
3. for key, value in phone_numbers.items():
4. print("{} has as phone number
{}".format(key, value))
In both cases the output is:
Output:
John Smith has as phone number +37682929928
Marry Simpons has as phone number +423998200919
Loops
In this section, you learned that:
For loops are useful for executing a command over a
large number of items.
You can create a for loop like so:
1. for letter in 'abc':
2. print(letter.upper())
Output:
A
B
C
The name after for (e.g. letter ) is just a variable name
You can loop over dictionary keys:
1. phone_numbers = {"John
Smith":"+37682929928","Marry
Simpons":"+423998200919"}
2. for value in phone_numbers.keys():
3. print(value)
Output:
John Smith
Marry Simpsons
You can loop over dictionary values:
1. phone_numbers = {"John
Smith":"+37682929928","Marry
Simpons":"+423998200919"}
2. for value in phone_numbers.values():
3. print(value)
Output:
+37682929928
+423998200919
You can loop over dictionary items:
1.phone_numbers = {"John
Smith":"+37682929928","Marry
Simpons":"+423998200919"}
2.for key, value in phone_numbers.items():
3. print(key, value)
Output:
('John Smith', '+37682929928')
('Marry Simpons', '+423998200919')
While loops will run as long as a condition is true:
1.while datetime.datetime.now() <
datetime.datetime(2090, 8, 20, 19, 30, 20):
2. print("It's not yet 19:30:20 of 2090.8.20")
The loop above will print out the string inside print() over
and over again until the 20th of August, 2090.
List Comprehensions
In this section, you learned that:
A list comprehension is an expression that creates a list by
iterating over another container.
A basic list comprehension:
1.[i*2 for i in [1, 5, 10]]
Output: [2, 10, 20]
List comprehension with if condition:
1.[i*2 for i in [1, -2, 10] if i>0]
Output: [2, 20]
List comprehension with an if and else condition:
1.[i*2 if i>0 else 0 for i in [1, -2, 10]]
Output: [2, 0, 20]
More on Functions
In this section, you learned that:
Functions can have more than one parameter:
1. def volume(a, b, c):
2. return a * b * c
Functions can have default parameters (e.g. coefficient ):
1. def converter(feet, coefficient = 3.2808):
2. meters = feet / coefficient
3. return meters
4.
5. print(converter(10))
Output: 3.0480370641306997
Arguments can be passed as non-keyword (positional) arguments
(e.g. a ) or keyword arguments (e.g. b=2 and c=10 ):
1. def volume(a, b, c):
2. return a * b * c
3.
4. print(volume(1, b=2, c=10))
An *args parameter allows the function to be called with an
arbitrary number of non-keyword arguments:
1. def find_max(*args):
2. return max(args)
3. print(find_max(3, 99, 1001, 2, 8))
Output: 1001
An **kwargs parameter allows the function to be called with an
arbitrary number of keyword arguments:
1. def find_winner(**kwargs):
2. return max(kwargs, key = kwargs.get)
3.
4. print(find_winner(Andy = 17, Marry = 19, Sim = 45, Kae = 34))
Output: Sim
Here's a summary of function elements:
File Processing
In this section, you learned that:
You can read an existing file with Python:
1. with open("file.txt") as file:
2. content = file.read()
You can create a new file with Python and write some text on it:
1. with open("file.txt", "w") as file:
2. content = file.write("Sample text")
You can append text to an existing file without overwriting it:
1. with open("file.txt", "a") as file:
2. content = file.write("More sample text")
You can both append and read a file with:
1. with open("file.txt", "a+") as file:
2. content = file.write("Even more sample text")
3. file.seek(0)
4. content = file.read()
Imported Modules
In this section, you learned that:
Builtin objects are all objects that are written inside the Python
interpreter in C language.
Builtin modules contain builtins objects.
Some builtin objects are not immediately available in the global
namespace. They are parts of a builtin module. To use those objects
the module needs to be imported first. E.g.:
1. import time
2. time.sleep(5)
A list of all builtin modules can be printed out with:
1. import sys
2. sys.builtin_module_names
Standard libraries is a jargon that includes both builtin modules
written in C and also modules written in Python.
Standard libraries written in Python reside in the Python installation
directory as .py files. You can find their directory path with sys.prefix .
Packages are a collection of .py modules.
Third-party libraries are packages or modules written by third-party
persons (not the Python core development team).
Third-party libraries can be installed from the terminal/command
line:
Windows:
pip install pandas or use python -m pip install pandas if that doesn't
work.
Mac and Linux:
pip3 install pandas or use python3 -m pip install pandas if that doesn't
work.
Solution: Making Version 1.2 of
the Program
Lines 8 and 9 were added to make sure the program returns the definition
of words that start with a capital letter (e.g., Delhi or Texas):
1. import json
2. from difflib import get_close_matches
3. data = json.load(open("data.json"))
4. def translate(w):
5. w = w.lower()
6. if w in data:
7. return data[w]
8. elif w.title() in data: #if user entered "texas" this will check for "Texas" as
well.
9. return data[w.title()]
10. elif len(get_close_matches(w, data.keys())) > 0:
11. yn = input("Did you mean %s instead? Enter Y if yes, or N if no: " %
get_close_matches(w, data.keys())[0])
12. if yn == "Y":
13. return data[get_close_matches(w, data.keys())[0]]
14. elif yn == "N":
15. return "The word doesn't exist. Please double check it."
16. else:
17. return "We didn't understand your entry."
18. else:
19. return "The word doesn't exist. Please double check it."
20.
21. word = input("Enter word: ")
22. output = translate(word)
23. if type(output) == list:
24. for item in output:
25. print(item)
26. else:
27. print(output)
You can read the comments I included in the code: I have added another
conditional in lines 8 and 9. The w.title() method will convert the first
letter to uppercase and the rest to lowercase. If the program didn't find
anything for "texas" in the first conditional in lines 6 and 7, then this
conditional will try to search for "Texas". Even if the user entered "TEXAS"
this conditional will convert it to "Texas".
Making Version 1.2 of the
Program
I added lines 10 and 11 to make sure the program returns the definition of
acronyms (e.g., USA or NATO.)
1. import json
2. from difflib import get_close_matches
3. data = json.load(open("data.json"))
4. def translate(w):
5. w = w.lower()
6. if w in data:
7. return data[w]
8. elif w.title() in data:
9. return data[w.title()]
10. elif w.upper() in data: #in case user enters words like USA or NATO
11. return data[w.upper()]
12. elif len(get_close_matches(w, data.keys())) > 0:
13. yn = input("Did you mean %s instead? Enter Y if yes, or N if no: " %
get_close_matches(w, data.keys())[0])
14. if yn == "Y":
15. return data[get_close_matches(w, data.keys())[0]]
16. elif yn == "N":
17. return "The word doesn't exist. Please double check it."
18. else:
19. return "We didn't understand your entry."
20. else:
21. return "The word doesn't exist. Please double check it."
22. word = input("Enter word: ")
23. output = translate(word)
24. if type(output) == list:
25. for item in output:
26. print(item)
27. else:
28. print(output)
More SQL Statements
In the example you just saw, we used the following SQL statement in our Python
code:
1. query = cursor.execute("SELECT * FROM Dictionary WHERE Expression = 'rain'")
That statement retrieved all the rows of the Dictionary table where the value of the
column Expression was rain. The string inside cursor.execute() is SQL code that
Python sends to the database. The database understands that kind of language.
Here are some more examples of SQL queries that you can try out from within
your Python script just like we did previously:
Get all rows where the value of the column Expression starts with r:
1. "SELECT * FROM Dictionary WHERE Expression LIKE 'r%'"
Get all rows where the value of the column Expression starts with rain:
1. "SELECT * FROM Dictionary WHERE Expression LIKE 'rain%'"
All rows where the length of the value of the column Expression is less than
four characters:
1. "SELECT * FROM Dictionary WHERE length(Expression) < 4"
All rows where the length of the value of the column Expression is four
characters:
1. "SELECT * FROM Dictionary WHERE length(Expression) = 4"
All rows where the length of the value of the column Expression is greater
than 1 but less than 4 characters:
1. "SELECT * FROM Dictionary WHERE length(Expression) > 1 AND length(Expression) < 4"
All rows of column Definition where the value of the column Expression
starts with r:
1. "SELECT Definition FROM Dictionary WHERE Expression LIKE 'r%'"
Loading JSON Files
In the previous lecture, you learned that you can load a CSV file with this
code:
1. import pandas
2. df1 = pandas.read_csv("supermarkets.csv")
Try loading the supermarkets.json file for this exercise
using read_json instead of read_csv .
The supermarkets.json file can be found inside the supermarkets.zip file
attached in the previous lecture.
Note
We are going to use Nominatim() in the next video. Nominatim() currently has
a bug. To fix this problem, whenever you see these lines in the next video:
1. from geopy.geocoders import Nominatim
2. nom = Nominatim()
change them to these
1. from geopy.geocoders import ArcGIS
2. nom = ArcGIS()
The rest of the code remains the same.
Note
In the next lecture, I use this in the code:
tiles = "Mapbox Bright"
Please use this instead:
tiles = "Stamen Terrain"
Mapbox Bright and Stamen Terrain are both types of basemaps, but
Mapbox Bright doesn't work anymore. Stamen Terrain works great, and you
will see it creates a beautiful relief map.