174 KiB
Executable file
Review¶
One key idea in programming is a variable. A variable is a name that refers to a value. It lets us reference the value, even if we do not know what it is. We can assign to variables in Python using the =
symbol.
Even though we are still working with simple code, we have already learned two key ideas of programming that let us build more complex systems through modularity.
The first is functions. We learned that code is organized in blocks.
The second idea is scope.
We also learned about exceptions.
x = 0
def foo(a):
return a
z = foo(x)
x = 0
def foo(x):
y = 100/x
print(x)
print(y)
return y
y = 32
z = foo(y)
print(x)
print(y)
Coding style¶
It is great if your code runs successfully! However, you are likely to want to run it again. (And even if not, it is good to practice "Doin' It Right".) Therefore, it is good to optimize it for readability and reuse. There is certainly a sense of style in software coding. It's good to develop your own sense of good style.
There is more one way to write correct code. (In fact, there are infinitely many ways.)
Depending on the programming language, and often depending on the project or environment, there are standard, "idiomatic" ways of doing things. You should prefer those - they make your code easier to read for others - and also yourself in the future.
It is useful to spend time refining code so that it looks simple and, ideally, is simple. Of course this is not always possible.
One stylistic rule that holds pretty much in every programming language is the principle "Don't Repeat Yourself" (DRY). If you need to change something, ideally you will only need to change it in one place in your code. Another way of saying this is that there should only be a "single source of truth".
The python package "black" is commonly used linter for making code style changes to an idiomatic format.
Style suggestions¶
- In general: simplify
- Remove irrelevant code (e.g.
plt.show;
) - Remove irrelevant comments (e.g.
# YOUR CODE HERE
)
Types¶
Every value in Python has a type. You don't usually see the types written, but it is critically important to understand what types are used in code you are working on. Python checks exactly how something is typed and, according to strict rules, decides what type the value will have. For example, these will all be different types:
10
10.0
'10'
Types of types¶
So far, we have mostly worked with whole numbers called integers - in python, an int
. We briefly saw None
and some strings. You may have also seen floating point numbers (float
in python).
Let's practice with some of these types.
Playing with types¶
10
type(10)
10.0
type(10.0)
x = 10
type(x)
type("10")
type('10')
my_string = "Hello, My name is Angela Merkel"
my_string = "übersetzen"
Übersetzung = "translation"
print(my_string)
my_string = 'the data is like this: "gcatcccggg"'
print(my_string)
my_string = "the data is like this: "gcatcccggg""
print(my_string)
my_string = "the data is like this: \"gcatcccggg\""
print(my_string)
my_string = "the data is like this: \\gcatcccggg\""
print(my_string)
my_string = 'the data is like this: \'gcatcccggg\''
print(my_string)
my_string = 'the data is like this: 'gcatcccggg''
print(my_string)
my_string = "the data is like this: 'gcatcccggg'"
print(my_string)
my_string = "the data is like this: \\ 'gcatcccggg'"
print(my_string)
x=10
print(x)
1234
def myprint(x):
print(x)
return 32
myprint("hello")
myprint("hello");
10
# In Jupyter, `_` is a special variable, which means the output value of the previously run cell.
y=_
y
x=x+1
print(x)
z=x=x+1
z
x
None type¶
The None
type is used when there is no value. It is actually very common in Python. For example a function which does not return anything actually returns the value None
.
x=None
print(x)
x=None
type(x)
None
10
x=print(10)
print(x)
x
x=10
x
Operators¶
Many of the most commonly used operations (like addition) could be written as function calls, but instead have special symbols (like +
).
3+4
int.__add__(3,4)
"abc" + "def"
str.__add__("abc", "def")
Complex expressions¶
Often we write expressions in which multiple operations happen in one line of code
4 * 3 + 2
2 + 4 * 3
x = 4 * 3 + 2
x
x = x * 2
x
y=4*3+2
y
tmp = 4*3
y = tmp+2
y
tmp = 'my super import data'
y=4*(3+2)
y
tmp
tmp2 = 'my super import data'
tmp=3+2
tmp2 = 4*tmp
y = tmp2
tmp2
print(y)
print(4*3+2)
x = [1,2,2,2,2,2,"three", 4.0]
print(x)
x=list()
print(x)
x=[1,2,3,4]
print(x)
x=[]
print(x)
x.append(1)
print(x)
x.append(2)
print(x)
x.append(3)
print(x)
z = x.append(4)
print(x)
print(z)
x=["red","green","blue"]
print(x)
x=["red", 101, "green", 202, "blue", 303]
print(x)
x=["red", 101, "green", 202, "blue", 303, [1,2,3], 'lkasjdf"laskdjfj']
print(x)
list indexing¶
x=["red","green","blue"]
x[0]
x=["red","green","blue"]
x[1]
x=["red","green","blue"]
x[2]
x=["red","green","blue"]
x[-1]
x=["red","orange","yellow","green","blue","indigo","violet"]
x[-1]
x=["red","orange","yellow","green","blue","indigo","violet"]
x[-3]
x
y=2
x[y]
x['hello']
x[1.23]
getting index of item in list¶
x=["red","orange","yellow","green","blue","indigo","violet"]
x.index("blue")
x.index(321)
setting an item in a list¶
x
x[3]=3
x
list slicing¶
x=["red","orange","yellow","green","blue","indigo","violet"]
x[0:3]
x[3]
x[:3]
x=["red","orange","yellow","green","blue","indigo","violet"]
x[None:3]
x[0:3]
x=["red","orange","yellow","green","blue","indigo","violet"]
x[3:]
x=["red","orange","yellow","green","blue","indigo","violet"]
x[3:None]
x=["red","orange","yellow","green","blue","indigo","violet"]
x[3:-1]
x = (1,2,3,4)
print(type(x))
print(x)
x = ()
print(type(x))
print(x)
x = (1,)
print(type(x))
print(x)
x = (1)
print(type(x))
print(x)
x = 1,
print(type(x))
print(x)
x = 1,2,3
print(type(x))
print(x)
x = 1
print(type(x))
print(x)
x = tuple()
print(type(x))
print(x)
x = tuple([1])
print(type(x))
print(x)
x = tuple([1,2,3,4])
print(type(x))
print(x)
x = tuple(1,2,3,4)
print(type(x))
print(x)
tmp = [1]
print(type(tmp))
x = tuple(tmp)
print(type(x))
print(x)
tuple indexing and slicing¶
x=("red","orange","yellow","green","blue","indigo","violet")
x[2]
x=("red","orange","yellow","green","blue","indigo","violet")
x[-1]
x=("red","orange","yellow","green","blue","indigo","violet")
x[-3]
x=("red","orange","yellow","green","blue","indigo","violet")
x[0:3]
x[:3]
lists are mutable, tuples are not¶
x=["red","orange","yellow","green","blue","indigo","violet"]
print(x)
x[3]=3
print(x)
x=("red","orange","yellow","green","blue","indigo","violet")
print(x)
x[3]=3
print(x)
passing mutable lists to functions¶
def modify_arg(a,b):
a.append(b)
# Notice that there is no return here!
# So, this function has an important "side effect",
# but the output is None.
x = [1,2,3]
y = modify_arg(x, 4)
x
print(y)
x
variables can be names pointing to an object in memory¶
x=["red","orange","yellow","green","blue","indigo","violet"]
y=x
print(x)
y[3]=3
print(y)
print(x)
x=0
y=x
print(x)
y=3
print(x)
print(y)
# View the previous example and then this one in pythontutor.com
x=["red","orange","yellow","green","blue","indigo","violet"]
y=x.copy()
print(x)
y[3]=3
print(y)
print(x)
Plotting¶
import matplotlib.pyplot as plt
x=[1,2,3,0,4,1]
y=[0,4,0,3,3,0]
plt.plot(x,y,"go-");
x=[1,2,3,0,4,1]
y=[0,4,0,3,3,0]
plt.plot(x,y);
y=[0,4,0,3,3,0]
plt.plot(y);
Cheatsheet for much more matplotlib: https://twitter.com/dr_shlee/status/1282772480046891010
Boolean (bool
) type¶
Python's bool
type can take one of two values: True
or False
. It is used to test a condition, such as in an if statement.
x = 1
y = x > 0
y
type(y)
x = -1
if x > 0:
print("x is positive")
x = 10
x
x>0
type(x>0)
x = 1
if x > 0:
y = 20
print("x is positive")
print("x is still positive")
else:
y = 40
print("x is negative")
print("x is still negative")
print("out of the blocks")
print(y)
Equality testing¶
Equality and comparisons¶
Comparison operators: ==
, >
, >=
, <
, <=
, !=
These operators take two arguments (left and right hand side) and return a boolean.
3 > 4
3 == 4
2+2 == 4
2+(2 == 4)
2+(False)
2+False
Coercion¶
explicit coersion¶
x = "10"
x
type(x)
x+32
x = int(x)
x
type(x)
x+32
bool(0)
bool(1)
bool("")
bool(" ")
bool(None)
bool("False")
bool(False)
str(False)
bool(str(False))
int(False)
int('False')
int(bool('False'))
int(False)
int(True)
implicit coersion¶
if 10:
print("10 is an integer, not a boolean. Why is this not an error?")
if 0:
print("why doesn't this print?")
x = "False"
if x:
print("hello")
x = ""
if x:
print("hello")
Python's assert
¶
assert True
assert False
bool(1)==True
assert bool(1)==True
assert bool(0)==True
assert bool(0)==True, "When I wrote this function, I assumed this would be otherwise."
Blocks and control flow¶
if True:
print("statement 1")
print("statement 2")
print("statement 3")
a = 1
b = -2
if a==1:
if b>0:
print("a is one and b is positive")
else:
print("here")
print("a is one")
else:
print("a is not one")
a = 1
b = -0.0
if a==1:
if b>0:
print("a is one and b is positive")
elif b<0:
print("a is one and b is negative")
else:
print("a is one")
print("b is zero")
else:
print("a is not one")
b