Python Crash Course
Python Crash Course
Data types
Numbers
1 + 1
1 * 3
1 / 2
0.5
2 ** 4
16
4 % 2
5 % 2
(2 + 3) * (5 + 5)
50
Variable Assignment
# Can not start with number or special characters
name_of_var = 2
x = 2
y = 3
z = x + y
Strings
'single quotes'
'single quotes'
"double quotes"
'double quotes'
Printing
x = 'hello'
'hello'
print(x)
hello
num = 12
name = 'Sam'
Lists
[1,2,3]
[1, 2, 3]
['hi',1,[1,2]]
my_list = ['a','b','c']
my_list.append('d')
my_list
my_list[0]
'a'
my_list[1]
'b'
my_list[1:]
my_list[:1]
['a']
my_list[0] = 'NEW'
my_list
nest = [1,2,3,[4,5,['target']]]
nest[3]
[4, 5, ['target']]
nest[3][2]
['target']
nest[3][2][0]
'target'
Dictionaries
d = {'key1':'item1','key2':'item2'}
d['key1']
'item1'
Booleans
True
True
False
False
Tuples
t = (1,2,3)
t[0]
t[0] = 'NEW'
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
<ipython-input-44-97e4e33b36c2> in <module>()
----> 1 t[0] = 'NEW'
Sets
{1,2,3}
{1, 2, 3}
{1,2,3,1,2,1,2,3,3,3,3,2,2,2,1,1,2}
{1, 2, 3}
Comparison Operators
1 > 2
False
1 < 2
True
1 >= 1
True
1 <= 4
True
1 == 1
True
'hi' == 'bye'
False
Logic Operators
(1 > 2) and (2 < 3)
False
(1 > 2) or (2 < 3)
True
(1 == 2) or (2 == 3) or (4 == 4)
True
Yep!
if 1 < 2:
print('yep!')
yep!
if 1 < 2:
print('first')
else:
print('last')
first
if 1 > 2:
print('first')
else:
print('last')
last
if 1 == 2:
print('first')
elif 3 == 3:
print('middle')
else:
print('Last')
middle
for Loops
seq = [1,2,3,4,5]
1
2
3
4
5
Yep
Yep
Yep
Yep
Yep
2
4
6
8
10
while Loops
i = 1
while i < 5:
print('i is: {}'.format(i))
i = i+1
i is: 1
i is: 2
i is: 3
i is: 4
range()
range(5)
range(0, 5)
for i in range(5):
print(i)
0
1
2
3
4
list(range(5))
[0, 1, 2, 3, 4]
list comprehension
x = [1,2,3,4]
out = []
for item in x:
out.append(item**2)
print(out)
[1, 4, 9, 16]
[1, 4, 9, 16]
functions
def my_func(param1='default'):
"""
Docstring goes here.
"""
print(param1)
my_func
<function __main__.my_func>
my_func()
default
my_func('new param')
new param
my_func(param1='new param')
new param
def square(x):
return x**2
out = square(2)
print(out)
lambda expressions
def times2(var):
return var*2
times2(2)
<function __main__.<lambda>>
map(times2,seq)
<map at 0x105316748>
list(map(times2,seq))
[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10]
<filter at 0x105316ac8>
[2, 4]
methods
st = 'hello my name is Sam'
st.lower()
st.split()
tweet.split('#')
tweet.split('#')[1]
'Sports'
d.keys()
dict_keys(['key2', 'key1'])
d.items()
lst = [1,2,3]
lst.pop()
lst
[1, 2]
'x' in [1,2,3]
False
'x' in ['x','y','z']
True
Great Job!