Contents
Python in 5 minutes
CodeThump “x in 5 minutes” guides really are 5 minute guides. We cut the crap and give you the essentials. To go further, check the links at the end.
You may want to start by setting up Python on your machine. Here’s a 3 step guide to installing Python 3 on a Mac.
We’ve also given you an interactive Python interpreter on this page. You can type commands in and execute them. Start with our examples (copy and paste into the interpreter) and then play around with your own changes.
OK, let’s learn Python in 5 minutes.
The Python language
- Dynamically typed
- Interpreted
- Whitespace indentation to create blocks
- Garbage collected
- Supports OO, functional, structured
- Duck typing
Python Booleans
- True
- False
Note capital T and capital F
Convert to an int gives 0 or 1 for True or False
Falsy types are:
- the constants None and False
- zero of any numeric type
- empty sequences or collections
int(True) # 1
int(False) # 0
bool(-1) # True
bool(0) # False
bool(1) # True
Python strings
Single or double quotes treated the same
Triple quotes for multi-line
There is no Character type – only a string of length 1
'mississippi'.capitalize() == 'Mississippi'
len('mississippi' ) == 11
'mississippi'.count('s') == 4
'mississippi'.replace('s', 'p') == 'mippippippi'
# Python uses zero indexing
'mississippi'.find('s') == 2
'cool'.center(10, '-') == '---cool---'
' '.isspace() == True
('s' in 'mississippi') == True
('x' not in 'mississippi') == True
'2020'.isdigit() == True
'mississippi'.isalpha() == True
# Joining a sequence of strings may look surprising
'-'.join(('a','b','c')) == 'a-b-c'
# Python strings support arithmetic operators
'missi'*2 == 'missimissi'
# Slice and range slice with square brackets
'mississippi'[1:5] == 'issi'
'mississippi'[5] == 's'
'mississippi'[:5] == 'missi'
'mississippi'[5:] == 'ssippi'
# String formatting
print ("Hello %s, you are student number %d" % ('Bart', 999))
Python conditionals
Uses indentation to create blocks
First statement of a block ends with colon
Write and, or, not instead of && etc – Python prefers explicitness and readability
if 99:
print('Yes') # Yes - non-zero number is truthy
else:
print('No')
# Logical operations as you would expect
if 5 > 3 and 5 < 6:
print('Yes') # Yes
else:
print('No')
# negation
if not 5 > 6:
print('Yes') # Yes
else:
print('No')
# Ternary conditionals
a = None
print ('yes') if a else ('no') # no
Python lists
Behaves like arrays in Java/JavaScript
Supports slice and index
Zero indexed
a = ['first', 'second', 'third']
a[1] == 'second'
a[1:] == ['second', 'third']
# negative indexes count backwards
a[-1] == 'third'
a[-2] == 'second'
a.append('fourth')
a.insert(2, 'second-ish')
a.remove('third')
a == ['first', 'second', 'second-ish', 'fourth']
'third' in a == False
len(a) == 4
Python dictionaries
Key,value pairs
country = {'abbrev': 'UK', 'full_name': 'United Kingdom', 'currency': 'Sterling'}
country['abbrev'] == 'UK'
country['currency'] = 'worthless'
country # prints {'abbrev': 'UK', 'full_name': 'United Kingdom', 'currency': 'worthless'}
country.keys() # prints dict_keys(['abbrev', 'full_name', 'currency'])
country.values() # prints dict_values(['UK', 'United Kingdom', 'worthless'])
Python equality and identity
is operator tests for identity
== tests for equality
(5 is 5 )== True
(5 is None) == False
a = 3
b = 4
c = a
(a is b) == False
(a is c) == True
(1 is True) == False
(1 == True) == True
Python loops
numbers = [1, 2, 3]
for number in numbers:
print(number)
# prints 1 2 3
for number in range(5,8):
print (number)
# prints 5 6 7
i = 0
while i < 2:
print(i)
i+= 1
# prints 0 1
Python functions
Use the def keyword
Allows default arguments
def spam():
print ('spam')
spam()
# prints spam
# Default arguments
def eggs(count=3):
for i in range(count):
print(i)
eggs()
# prints 0 1 2
eggs(4)
# prints 0 1 2 3
Python classes
Use class keyword
Method’s self argument is provided implicitly by the call
self is a convention not a keyword
Members are public, there is no private
By convention underscore prefix implies should be considered non-public
Methods call other methods using self.method_name()
Python classes can have instance, class, and static methods
Classes are objects
class SomeClass:
var1 = 'class variable'
def __init__(self, var2):
self.var2 = var2
def get_var2(self):
return self.var2
instance = SomeClass('instance variable')
print(instance.get_var2()) # prints instance variable
print(instance.var1) # prints class variable
Python namespaces and scope
Python starts with the built-in namespace including functions like print.
Define a module and that creates a global namespace.
Define a function and that creates a local namespace.
A nested function has a nested namespace.
The local namespace is inside the global namespace which is inside the built-in namespace.
Inside a function, variables defined in that function are in local scope and we can read and write them. Variables outside are in non-local or global scope. We can read them, but attempting to write actually creates a new local variable with the same name.
def outer():
a = 2
def inner():
a = 3
print(a)
inner()
print(a)
a =1
outer()
print(a)
# prints 3 2 1
#You can select scope using the nonlocal or global keywords
a=1
def outer():
global a
a = 2
b = 1
def inner():
nonlocal b
b = 2
print(b)
inner()
print(a)
outer()
print(a)
# prints 2 2 2
Learn Python
Well, that was Python in 5 minutes. Of course there’s a lot more. Dig in.