Code for integer division in Python 2:
3 / 4
Code for float division in Python 2:
3 / 4.
Code for integer division in Python 3:
3 // 4
Code for float division in Python 3:
3 / 4
Create a string with single quotes in Python:
my_ball = "Will's ball"
Create a multiline string in Python:
multiline = """Will's ball
is red
and bouncy!"""
Code to escape a single quote in Python:
print("Will's ball is red")
or
print('Will\'s ball is red')
or
print("""Will's ball is red""")
Code to print tab characters in Python:
print("Will's\tball\tis\tred")
Code to use variable substitution in a string:
item = 'ball'
color = 'red'
print("Will's %s is %s." % (item, color))
Code to use variable substitution with the string format method:
item = 'ball'
color = 'red'
print("Will's {0} is {1}".format(item, color))
Code to use the .endswith method:
"The ball is red".endswith("red")
Code to find a string within a string:
"The ball is red".find("is")
Code to join strings together in Python:
" ".join(["the", "ball", "is", "red"])
Code to strip spaces from the beginning and end of a string in Python:
" Will ".strip()
Code to strip spaces from the beginning of a string in Python:
" Will ".lstrip()
Code to strip spaces from the end of a string in Python:
" Will ".rstrip()
Use the dir method to find the methods available:
dir("Will")
Use the help method to find out how to use a method:
help("Will".rstrip)
Use an if
statement in Python:
x = int(input("enter an integer: "))
if x < 0:
x = 0
print("Negative number changed to zero")
Use an elif
statement in Python:
x = int(input("enter an integer: "))
if x < 0:
x = 0
print("Negative number changed to zero")
elif x == 0:
print("zero")
elif x == 1:
print("one")
else:
print("Some other number")
Use a for
statement in Python:
pets = ['cat', 'dog', 'elephant']
for pet in pets:
print('I have a pet {0}.format(pet))
Use for
with a range of numbers in Python:
for i in range(5):
print(i)
Use a while
statement in Python:
x = 1
while x < 10:
print(x)
x = x + 1
Terminate a loop with a break
statement in Python:
pets = ['cat', 'dog', 'elephant']
for pet in pets:
if pet == 'dog':
print("No dogs allowed")
break
else:
print("We love {0}.format(pet))
Test for equality in Python:
5 == 5
returns True
Test for inequality in Python:
5 != 4
returns True
Test for greater than in Python:
5 > 3
returns True
Test for less than in Python:
3 < 5
returns True
Test for greater than or equal to in Python:
5 >= 5
returns True
Use chaining to test multiple conditions in Python:
3 < x < 5
returns True
Test to see if an object is a given type:
isinstance("will", str)
returns True
isinstance("will", int)
returns False
Test to see if an object is the exact same with the is
operator:
a = True
b = True
a is b # returns True
x = [1, 2, 3]
y = [1, 2, 3]
x is y # returns Flase
Use the in
operator to check if a value is present:
x = [1, 2, 3]
3 in x # returns True
5 in x # returns False
Iterate over a list and test for conditional values:
x = [1, 2, 3]
for value in x:
if value == 2:
print('Value is 2!')
car = {'model': 'Chevy', 'year': 1970, 'color': 'red'}
if 'model' in car:
print('This is a {0}'.format(car['model']))
Create a list in Python:
a = [1, 2, 3, 4]
b = [1, 'cat', 7, {'car': 'chevy'}]
Access an individual item by index number in Python:
b[0] # prints the first item in the list
b[1] # prints the second item in the list
Append items to a list:
pets = []
pets.append('cat')
pets.append('dog')
pets.append('bear')
pets.append('shark')
Remove an item from a list:
pets.remove('dog')
Use the pop
method to remove the last item from a list:
pets.pop()
Use the pop
method to specify an item to remove by index number:
pets.pop(0) # removes cat from the list
Use the sort
method to sort items in a list:
pets = ['cat', 'dog', 'bear', 'shark']
pets.sort()
pets # returns ['bear', 'cat', 'dog', 'shark']
Use the reverse
method to reverse the list:
pets.reverse() # returns ['shark', 'dog', 'cat', 'bear']
Get the number of items in a list:
len(pets) # returns 4
Get the number of occurrences of an item in a list:
pets.count('bear') # returns 1
Slice a list in Python:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a[2:5] # returns [3, 4, 5]
a[2:] # returns [3, 4, 5, 6, 7, 8, 9]
a[:5] # returns [1, 2, 3, 4, 5]
a[-4:] # returns [6, 7, 8, 9]
Use slice to replace part of a list in Python:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a[2:5] = ['foo', 'bar', 'baz']
a # returns [1, 2, 'foo', 'bar', 'baz', 6, 7, 8, 9]
Use list comprehension to create a new list with items not found in the second list:
zoo_animals = ['giraffe', 'monkey', 'elephant', 'lion', 'bear', 'pig', 'horse', 'aardvark']
my_animals = ['monkey', 'bear', 'pig']
other_animals = [animal for animal in zoo_animals if animal not in my_animals]
Use list comprehension to create a new list after each list item is modified:
sales = [3.14, 7.99, 10.99, 0.99, 1.24]
sales = [sale * 1.07 for sale in sales]
Create a dictionary and add values to it in Python:
age = {}
age['will'] = 40
age['bob'] = 30
age['john'] = 20
age # returns {'will': 40, 'bob': 30, 'john': 20}
Access the value for a specific key in the dictionary:
print(age['will']) # returns 40
Check to see if a key is present in the dictionary:
'will' in age # returns True
'austin' in age # returns False
Delete a key/value pair from a dictionary:
del age['bob']
Use the get
method to retrieve a value or a default value if not found:
print(age.get('will', 'Key not found')) # returns 40
print(age.get('austin', 'Key not found')) # returns Key not found
Iterate the key value pairs in a dictionary:
for key, value in age.items():
print(key, value)
Create a tuple in Python:
t = 'dog', 'cat', 12345
t # returns ('dog', 'cat', 12345)
Access a tuple value by index id:
t[0] # returns 'dog'
t[1] # returns 'cat'
Create a set in Python:
animals = {'monkey', 'bear', 'dog', 'monkey', 'cat', 'bear', 'gorilla'}
animals # returns {'monkey', 'bear', 'gorilla', 'dog', 'cat'}
Check if a value is present in a set:
'monkey' in animals # returns True
'shark' in animals # returns False
Create an empty set in Python:
fish = set()
Add items to a set:
fish.add('shark')
fish.add('guppy')
fish.add('whale')
Remove items from a set:
fish.remove('whale')
Use union to combine two sets into a single, deduplicated set:
fish.union(animals) # returns {'guppy', 'monkey', 'bear', 'shark', 'gorilla', 'dog', 'cat'}
Display a list of methods and operators for a string in Python:
dir('foo')
Display the help page for a given method:
help("foo".upper)