- ctrl + l : clear python shell
- exit() : exit python shell
- python3 my_python_script.py : run a python script (for osx users)
rank = 10
eggs = 12
people = 3
temperature = 10.2
rainfall = 5.98
elevation = 1031.88
message = "Welcome to our online shop!"
name = "John"
serial = "R001991981SW"
members = ["Sim Soony", "Marry Roundknee", "Jack Corridor"]
pixel_values = [252, 251, 251, 253, 250, 248, 247]
phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"}
volcano_elevations = {"Glacier Peak": 3213.9, "Rainer": 4392.1}
phone_numbers.keys()
phone_numbers.values()
vowels = ('a', 'e', 'i', 'o', 'u')
one_digits = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
dir(str)
dir(list)
dir(dict)
dir(__builtins__)
help(str)
help(str.replace)
help(dict.values)
["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
0 1 2 3 4 5 6
["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
-7 -6 -5 -4 -3 -2 -1
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
days[1:4]
Output: ['Tue', 'Wed', 'Thu']
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
days[:3]
Output:['Mon', 'Tue', 'Wed']
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
days[-3:]
Output: ['Fri', 'Sat', 'Sun']
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
days[:-1]
Output: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
days[:-2]
Output: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
phone_numbers = {"John Smith":"+37682929928","Marry Simpons":"+423998200919"}
phone_numbers["Marry Simpsons"]
Output: '+423998200919'
Using "and" and "or" in a Conditional
x = 1
if x == 1:
print("Yes")
else:
print("No")
x = 1
y = 1
if x == 1 and y==1:
print("Yes")
else:
print("No")
That will return Yes since x == 1 and y ==1 are both True.
x = 1
y = 1
if x == 1 or y==2:
print("Yes")
else:
print("No")
That will return Yes since at least one of the conditions is True. In this case x == 1 is True.
def cube_volume(a):
return a * a * a
message = "hello there"
if "hello" in message:
print("hi")
else:
print("I don't understand")
message = "hello there"
if "hello" in message:
print("hi")
elif "hi" in message:
print("hi")
elif "hey" in message:
print("hi")
else:
print("I don't understand")
x = 1
y = 1
if x == 1 and y==1:
print("Yes")
else:
print("No")
Output is Yes since both x and y are 1.
x = 1
y = 2
if x == 1 or y==2:
print("Yes")
else:
print("No")
Output is Yes since x is 1.
isinstance("abc", str)
isinstance([1, 2, 3], list)
or
type("abc") == str
type([1, 2, 3]) == lst
The input function halts the execution of the program and gets text input from the user
name = input("Enter your name: ")
experience_months = input("Enter your experience in months: ")
experience_years = int(experience_months) / 12
name = "Sim"
experience_years = 1.5
print("Hi %s, you have %s years of experience." % (name, experience_years))
Output: Hi Sim, you have 1.5 years of experience.
name = "Sim"
experience_years = 1.5
print("Hi {}, you have {} years of experience".format(name, experience_years))
Output: Hi Sim, you have 1.5 years of experience.
Let's suppose we defined this function:
def celsius_to_kelvin(cels):
return cels + 273.15
That is a function that gets a number as input, adds 273.15 to it and returns the result.
monday_temperatures = [9.1, 8.8, -270.15]
for temperature in monday_temperatures:
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).
Combine a dictionary for loop with string formatting to create text containing information from the dictionary:
phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"}
for pair in phone_numbers.items():
print("{} has as phone number {}".format(pair[0], pair[1]))
Another (better) way to do it::
phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"}
for key, value in phone_numbers.items():
print("{} has as phone number {}".format(key, value))
In both cases the output is:
- John Smith has as phone number +37682929928
- Marry Simpons has as phone number +423998200919
for letter in 'abc':
print(letter.upper())
Output:
- A
- B
- C
The name after for (e.g. letter) is just a variable name
phone_numbers = {"John Smith":"+37682929928","Marry Simpons":"+423998200919"}
for value in phone_numbers.keys():
print(value)
Output:
- John Smith
- Marry Simpsons
phone_numbers = {"John Smith":"+37682929928","Marry Simpons":"+423998200919"}
for value in phone_numbers.values():
print(value)
Output:
- +37682929928
- +423998200919
phone_numbers = {"John Smith":"+37682929928","Marry Simpons":"+423998200919"}
for key, value in phone_numbers.items():
print(key, value)
Output:
- ('John Smith', '+37682929928')
- ('Marry Simpons', '+423998200919')
while datetime.datetime.now() < datetime.datetime(2090, 8, 20, 19, 30, 20):
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.
A list comprehension is an expression that creates a list by iterating over another container.
[i*2 for i in [1, 5, 10]]
Output: [2, 10, 20]
[i*2 for i in [1, -2, 10] if i>0]
Output: [2, 20]
[i*2 if i>0 else 0 for i in [1, -2, 10]]
Output: [2, 0, 20]
def volume(a, b, c):
return a * b * c
def converter(feet, coefficient = 3.2808):
meters = feet / coefficient
return meters
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)
def volume(a, b, c):
return a * b * c
print(volume(1, b=2, c=10))
An *args parameter allows the function to be called with an arbitrary number of non-keyword arguments
def find_max(*args):
return max(args)
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
def find_winner(**kwargs):
return max(kwargs, key = kwargs.get)
print(find_winner(Andy = 17, Marry = 19, Sim = 45, Kae = 34))
Output: Sim
with open("file.txt") as file:
content = file.read()
with open("file.txt", "w") as file:
content = file.write("Sample text")
with open("file.txt", "a") as file:
content = file.write("More sample text")
with open("file.txt", "a+") as file:
content = file.write("Even more sample text")
file.seek(0)
content = file.read()
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.:
import time
time.sleep(5)
A list of all builtin modules can be printed out with:
import sys
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
Mac and Linux:
pip3 install pandas
if not any(website in line for website in website_list) part in the previous video, here is another example:
>>> lines = ["trees are good", "pool is fresh", "face is round"]
>>> website_list = ["face", "clock", "trend"]
>>> for line in lines:
... any(website in line for website in website_list)
...
False
False
True
We start iterating over the items of website_list using a for loop. In the first iteration we would have:
any(website in "trees are good" for website in website_list)
Inside the parenthesis of any() there's another loop that iterates over website_list:
("face" in "trees are good")
("clock" in "trees are good")
("trend" in "trees are good")
If any of the above is True you get the expression evaluated to True. In this case none of them is True, so you get False.
If you want to return True (if all of them are True), use all() instead of any().
So, the part any(website in line for website in website_list) will either be equal to True or False.
pip3 freeze
For some reasons, an imported module in your favorite terminal may be not found in the terminal of your favorite IDE. It's then interested to check the python version of IDE's terminal.
Francois at Mycomputer in ~/WorkspacePython/app4/webapp (master●●)
$ python3
Python 3.7.6 (default, Dec 30 2019, 19:38:26)
[Clang 11.0.0 (clang-1100.0.33.16)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.version
'3.7.6 (default, Dec 30 2019, 19:38:26) \n[Clang 11.0.0 (clang-1100.0.33.16)]'
>>> sys.executable
'/usr/local/opt/python/bin/python3.7'
>>>
Both python version should be the same (3.7 in this specific case)