0% found this document useful (0 votes)
5 views11 pages

python_cheat_sheet

The document outlines various programming concepts including math operators, string manipulation, data types, control flow statements, and dictionary operations. It provides examples of how to use different operators, loops, and functions in Python. Additionally, it covers methods for managing lists and dictionaries, such as adding, removing, and accessing elements.

Uploaded by

ffriispetersen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views11 pages

python_cheat_sheet

The document outlines various programming concepts including math operators, string manipulation, data types, control flow statements, and dictionary operations. It provides examples of how to use different operators, loops, and functions in Python. Additionally, it covers methods for managing lists and dictionaries, such as adding, removing, and accessing elements.

Uploaded by

ffriispetersen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Math Operators Concatenation and Replication

(highest to lowest precedence) String concatenation:


>>> ’Jerry’ ‘Smith’
Operators Operation Example
# ’JerrySmith’
** Exponent 2 ** 3 =
8 String replication:
>>> ‘Jerry’ * 3
% Modulus/ 22 % 8 =
# ‘JerryJerryJerry’
Remainder 6

// Integer 22 // 8 = The end keyword


division 2 Used to avoid the newline after
the output, or end the output with
/ Division 22 / 8 =
a different string.
2.75

* Multiplic 3 * 3 = 9 phrase = [‘printed’, ‘with’, ‘a’,


ation ‘dash’, ‘in’, ‘between’]
for word in phrase:
- Subtracti 5 - 2 = 3
​ print(word, end=’-’)
on

+ Addition 2 + 2 = 4 # printed-with-a-dash-in-between

The sep keyword


Augmented Assignment Operators
To specify how to separate the
Operator Equivalent objects, if there is more than
one.
‘var += 1’ var = var + 1

‘var -= 1’ var = var - 1 print(‘cats’, ‘dogs’, ‘ducks’,


sep=’,’)
‘var *= 1’ var = var * 1
# cats,dogs,ducks
‘var /= 1’ var = var / 1

‘var %= 1’ var = var % 1 The len() function


Evaluates the integer value of the
number of characters in a string,
Data Types
list, dictionary, etc.
Data type Examples
>>> len(‘hello’)
Integers -2, -1, 0, 1,
2, 3, 4 # 5

Float-point -1.25, -1.0, >>> len([‘dog’, 3, ‘cat’])


number 0.0, 0.5, 1.5 # 3

Strings ‘a’, ‘aa’,


‘Hey!’, ‘11
little cats’
Test of emptiness example: Ternary Conditional Operator
a = [1, 2, 3] Offers a one-line code solution to
evaluate the first expression if
# bad the condition is true, and
if len(a) > 0: # evaluates to True otherwise it evaluates the second
​ print(“list isn’t empty”) expression.

# good age = 16
if a: # evaluates to True
​ print(“list isn’t empty”) # this if statement:
if age < 18:
The str(), int(), and float() ​ print(‘kid’)
functions else:
Used to change the data type of a ​ print(‘adult’)
variable. # output: kid

>>> str(29) # is equivalent to this ternary


# ‘29’ operator:
print(‘kid’ if age < 18 else
>>> str(-3.14) ‘adult’)
# ‘-3.14’ # output: kid

>>> int(‘11’) Ternary operators can be chained:


# 11
age = 16
>>> float(‘3.14’)
# 3.14 # this if statement:
if age < 18:
Comparison Operators ​ if age < 13:
​ ​ print(‘kid’)
Operator Meaning
else:
‘==’ Equal to ​ ​ print(‘teen’)
else:
‘!=’ Not equal to ​ print(‘adult’)
# output: teen
‘<’ Less than

‘>’ Greater than # is equivalent to this ternary


operator:
‘<=’ Less than or print(‘kid’ if age < 18 else
equal to
‘teen’ if age < 18 else ‘adult’)
‘>=’ Greater than or
equal to

These operators return a boolean


(True or False) value.
While loop statements For loop
Used for repeated execution as Iterates over a list, tuple,
long as an expression is ‘True’. dictionary, set or string.

spam = 0 pets = [‘Oskar’, ‘Hermoine’, ‘Ay’]


while spam < 5: for pet in pets:
​ print(‘printing.’) ​ print(pet)
​ spam = spam + 1
# printing. # Oskar
# printing. # Hermoine
# printing. # Ay
# printing.
# printing. The range() function
Returns a sequence of numbers.
Break statements Starts from 0, increments by 1,
If the execution reaches this and stops before a specified
statement, it immediately exits number:
the loop.
for i in range(5):
while True: ​ print(f’Stop at 4? ({i})’)
​ name = input(‘Name: ‘)
​ if name == ‘your name’: # Stop at 4? (0)
​ ​ break # Stop at 4? (1)
# Stop at 4? (2)
print(‘Thank you!’) # Stop at 4? (3)
# Name: your name # Stop at 4? (4)
# Thank you!
The range() function can also
Continue statements modify its three default
When reached, the program arguments. First two arguments
execution jumps back to the start will be start and stop, and the
of the loop. third will be step. Step is the
amount the variable is increased
while True: by after each iteration.
​ name = input(‘Who are you?’)
​ if name != ‘Bob’: for i in range(0, 10, 2):
​ ​ continue ​ print(i)
​ password = input(‘Enter: ‘)
​ if password == ‘nemo’: # 0
​ ​ break # 2
# 4
print(‘Access granted.’) # 6
# Who are you? Brian # 8
# Who are you? Gregor
# Who are you? Philip
# Enter: nemo
# Access granted.
Negative values can be used for Negative indexes
step arguments too! furniture = [‘table’, ‘chair’,
‘rack’, ‘shelf’]
for i in range(5, -1, -1):
​ print(i) >>> furniture[-1]
# ‘shelf’
# 5
# 4 >>> furniture[-3]
# 3 # ‘chair’
# 2
# 1 >>> f’The {furniture[-1]} is
# 0 bigger than the {furniture[-3]}’
# ‘The shelf is bigger than the
For else statement chair’
Allows to specify a statement to
execute in case of a loop being Getting sublists with slices
fully executed. furniture = [‘table’, ‘chair’,
‘rack’, ‘shelf’]
for i in [1, 2, 3, 4, 5]:
​ if i == 3: >>> furniture[0:4]
​ ​ break # [‘table’, ‘chair’, ‘rack’,
else: ‘shelf’]
​ print(‘only executed when no
item is equal to 3’) >>> furniture[1:3]
# [‘chair’, ‘rack’]
Keyword arguments
def say_hi(name, greeting): >>> furniture[0:-1]
​ print(f’{greeting} {name}’) # [‘table’, ‘chair’, ‘rack’]

# Without keyword argument >>> furniture[:2]


say_hi(‘John’, ‘Hello’) # [‘table’, ‘chair’]
# Hello John
>>> furniture[1:]
# With keyword arguments # [‘chair’, ‘rack’, ‘shelf’]
say_hi(name=’Anna’, greeting=’Hi’)
# Hi Anna >>> furniture[:]
# [‘table’, ‘chair’, ‘rack’,
Getting values with indexes ‘shelf’]
furniture = [‘table’, ‘chair’,
‘rack’, ‘shelf’]

>>> furniture[0]
# ‘table’

>>> furniture[2]
# ‘rack’
Slicing the complete list will Getting the index in a loop with
perform a copy: enumerate()
furniture = [‘table’, ‘chair’,
spam2 = spam[:] ‘rack’, ‘shelf’]
# [‘cat’, ‘bat’, ‘rat’, ‘giraffe’]
for index, item in
>>> spam.append(‘dog’) enumerate(furniture):
>>> spam ​ print(f’index: {index} -
# [‘cat’, ‘bat’, ‘rat’, ‘giraffe’, item: {item}’)
‘dog’] # index: 0 - item: table
# index: 1 - item: chair
>>> spam2 # index: 2 - item: rack
# [‘cat’, ‘bat’, ‘rat’, ‘giraffe’] # index: 3 - item: shelf

Changing values with indexes The in and not in operators


furniture = [‘table’, ‘chair’, >>> ‘rack’ in [‘table’, ‘chair’,
‘rack’, ‘shelf’] ‘rack’, ‘shelf’]
# True
>>> furniture[0] = ‘desk’
>>> furniture >>> ‘bed’ in [‘table’, ‘chair’,
# [‘desk’, ‘chair’, ‘rack’, ‘rack’, ‘shelf’]
‘shelf’] # False

>>> furniture[2] = furniture[1] The multiple assignment trick


>>> furniture furniture = [‘table’, ‘chair’,
# [‘desk’, ‘chair’, ‘chair’, ‘rack’, ‘shelf’]
‘shelf’] table, chair, rack, shelf =
furniture
>>> furniture[-1] = ‘bed’
>>> furniture >>> table
# [‘desk’, ‘chair’, ‘chair’, # ‘table’
‘bed’]
>>> rack
Concatenation and Replication # ‘rack’
>>> [1, 2, 3] + [‘A’, ‘B’, ‘C’]
# [1, 2, 3, ‘A’, ‘B’, ‘C’] This trick can also be used to
swap the values in two variables.
>>> [‘X’, ‘Y’, ‘Z’] * 3
# [‘X’, ‘Y’, ‘Z’, ‘X’, ‘Y’, ‘Z’, >>> a, b = ‘table’, ‘chair’
‘X’, ‘Y’, ‘Z’] >>> a, b, = b, a
>>> print(a)
>>> my_list = [1, 2, 3] # chair
>>> my_list = my_list + [‘A’, ‘B’,
‘C’] >>> print(b)
>>> my_list # table
# [1, 2, 3, ‘A’, ‘B’, ‘C’]
The index method remove() - removes an item using
Allows you to find the index of a the actual value of it.
value by passing its name.
>>> furniture = [‘table’, ‘chair’,
furniture = [‘table’, ‘chair’, ‘rack’, ‘shelf’]
‘rack’, ‘shelf’] >>> furniture.remove(‘chair’)
>>> furniture
furniture.index(‘chair’) # [‘table’, ‘rack’, ‘shelf’]
# 1
Sorting values with sort()
Adding values >>> numbers = [2, 5, 3.14, 1, -7]
append() - Adds an element to the >>> numbers.sort()
end of a list. >>> numbers
# [-7, 1, 2, 3.14, 5]
>>> furniture = [‘table’, ‘chair’,
‘rack’, ‘shelf’] >>> furniture = [‘table’, ‘chair’,
>>> furniture.append(‘bed’) ‘rack’, ‘shelf’]
>>> furniture >>> furniture.sort(‘chair’)
# [‘table’, ‘chair’, ‘rack’, >>> furniture
‘shelf’, ‘bed’] # [‘chair’, ‘rack’, ‘shelf’,
‘table’]
insert() - Adds an element to a
list in a given position. You can also pass True for the
reverse keyword argument to have
>>> furniture = [‘table’, ‘chair’, sort() sort the values in reverse
‘rack’, ‘shelf’] order:
>>> furniture.insert(1, ‘bed’)
>>> furniture >>> furniture.sort(reverse=True)
# [‘table’, ‘bed’, ‘chair’, >>> furniture
‘rack’, ‘shelf’] # [‘table’, ‘shelf’, ‘rack’,
‘chair’]
Removing values
del() - removes an item using the If you need to sort the values in
index. regular alphabetical order, pass
str.lower for the key keyword
>>> furniture = [‘table’, ‘chair’, argument in the sort() method
‘rack’, ‘shelf’] call:
>>> del furniture[2]
>>> furniture >>> letters = [‘a’, ‘z’, ‘A’, ‘Z’]
# [‘table’, ‘chair’, ‘shelf’] >>> letters.sort(key=str.lower)
>>> letters
>>> del furniture[2] # [‘a’, ‘A’, ‘z’, ‘Z’]
>>> furniture
# [‘table’, ‘chair’]
You can use the built-in function values()
sorted to return a new list: >>> pet = {‘color’: ‘red’, ‘age’:
42}
>>> furniture = [‘table’, ‘chair’, >>> for value in pet.values():
‘rack’, ‘shelf’] ​ print(value)
>>> sorted(furniture) # red
# [‘chair’, ‘rack’, ‘shelf’, # 42
‘table’]
keys()
Converting between list() and >>> pet = {‘color’: ‘red’, ‘age’:
tuple() 42}
>>> tuple([‘cat’, ‘dog’, 5]) >>> for key in pet():
# (‘cat’, ‘dog’, 5) ​ print(key)
# color
>>> list((‘cat’, ‘dog’, 5)) # age
# [‘cat’, ‘dog’, 5]
items()
>>> list(‘hello’) Returns the items of a dictionary
# [‘h’, ‘e’, ‘l’, ‘l’, ‘o’] and returns them as a tuple.

Dictionaries >>> pet = {‘color’: ‘red’, ‘age’:


Set key, value using subscript 42}
operator [] >>> for item in pet.items():
>>> my_cat = { ​ print(item)
​ ‘size’: ‘fat’, # (‘color’, ‘red’)
​ ‘color’: ‘gray’, # (‘age’, 42)
​ ‘disposition’: ‘loud’,
​ } Using the keys(), values(), and
>>> my_cat[‘age_years’] = 2 items() methods, a for loop can
>>> print(my_cat) iterate over the keys, values, or
# {'size': 'fat', 'color': 'gray', key-value pairs in a dictionary.
'disposition': 'loud',
'age_years': 2} >>> pet = {‘color’: ‘red’, ‘age’:
42}
Retrieve value using subscript >>> for key, value in pet.items():
operator [] ​ print(f’Key: {key} Value:
>>> my_cat = { {value}’)
​ ‘size’: ‘fat’, # Key: color Value: red
​ ‘color’: ‘gray’, # Key: age Value: 42
​ ‘disposition’: ‘loud’,
​ }
>>> print(my_cat[‘size’)
# fat
get() clear() - removes all items in a
Returns the value of an item with dictionary.
the given key. If the key doesn’t
exist, it returns None. >>> wife = {‘name’: ‘Rose’, ‘age’:
33, ‘hair’: ‘brown’}
>>> wife = {‘name’: ‘Rose’, ‘age’: >>> wife.clear()
33} >>> wife
# {}
>>> f’My wife name is
{wife.get(“name”)}’ Checking keys in a dictionary
# ‘My wife name is Rose’ >>> person = {‘name’: ‘Rose’,
‘age’: 33}
Removing items
pop() - removes and returns an >>> ‘name’ in person.keys()
item based on a given key. # True

>>> wife = {‘name’: ‘Rose’, ‘age’: >>> ‘height’ in person.keys()


33, ‘hair’: ‘brown’} # False
>>> wife.pop(‘age’)
# 33 Checking values in a dictionary
>>> wife >>> person = {‘name’: ‘Rose’,
# {‘name’: ‘Rose’, ‘hair’: ‘age’: 33}
‘brown’}
>>> ‘Rose’ in person.values()
popitem() - removes the last item # True
in a dictionary and returns it.
>>> 33 in person.values()
>>> wife = {‘name’: ‘Rose’, ‘age’: # True
33, ‘hair’: ‘brown’}
>>> wife.popitem() List comprehension
# (‘hair’: ‘brown’) This is how we can create a new
>>> wife list from an existing collection
# {‘name’: ‘Rose’, ‘age’: 33} with a for loop.

del() - removes an item based on a >>> names = [‘Charles’, ‘Susan’,


given key. ‘Larry’, ‘George’]

>>> wife = {‘name’: ‘Rose’, ‘age’: >>> new_list = []


33, ‘hair’: ‘brown’} >>> for n in names:
>>> del wife[‘age’] ​ new_list.append(n)
>>> wife
# {‘name’: ‘Rose’, ‘hair’: >>> new_list
‘brown’} # [‘Charles’, ‘Susan’, ‘Larry’,
‘George’]
The same can be achieved with list Manipulating strings
comprehension. Escape characters
Is created by typing a backslash
>>> names = [‘Charles’, ‘Susan’, (\) followed by the character you
‘Larry’, ‘George’] want to insert.

>>> new_list = [n for n in names]


Escape Prints as:
>>> new_list character:
# [‘Charles’, ‘Susan’, ‘Larry’,
‘George’] \’ Single quote

\” Double quote
The same can be done with numbers.
\t Tab
>>> n = [(a, b) for a in range(1,
3) for b in range(1, 3)] \n Newline (line
>>> n break)
# {(1, 1), (1, 2), (2, 1), (2, 2)]
\\ Backslash

Adding conditionals \b Backspace


If we want to make a new list with
names that only start with C, we \ooo Octal value
use a for loop in the following \r Carriage Return
way:

>>> print(“Hello there!\nGeneral


>>> names = [‘Charles’, ‘Susan’,
Kenobi.\nYou are a bold one.”)
‘Larry’, ‘George’, ‘Mike’]
# Hello there!
# General Kenobi.
>>> new_list = []
# You are a bold one.
>>> for n in names:
​ if n.startswith(‘C’):
Raw strings
​ ​ new_list.append(n)
Entirely ignores all escape
characters and prints any
>>> print(new_list)
backslash that appears in the
# [‘Charles’, ‘Carol’]
string.
Or with using list comprehension:
>>> print(r“Hello there!\nGeneral
Kenobi.\nYou are a bold one.”)
>>> new_list = [n for n in names
# Hello there!\nGeneral
if np.startswith(‘C’)]
Kenobi.\nYou are a bold one.
>>> print(new_list)
# [‘Charles’, ‘Carol’]
Indexing
>>> spam = ‘Hello world!’
>>> spam[0]
# ‘H’
>>> spam[-1]
# ‘!’
Slicing startswith() and endswith()
>>> spam = ‘Hello world!’ >>> ‘Hello
>>> spam[0:5] world!’.startswith(‘Hello’)
# ‘Hello’ # True
>>> spam[:5]
# ‘Hello’ >>> ‘abc123’.startswith(‘abcdef’)
>>> spam [6:] # False
# ‘world’
>>> spam[6:-1] join() and split()
# ‘world’ join() - Takes all the items in an
>>> spam[:-1] iterable and joins them into a
# ‘Hello world’ string.
>>> spam[::-1]
# ‘!dlrow olleH’ >>> ‘’.join([‘My’, ‘name’, ‘is’,
‘Philip’])
The in and not in operator # ‘MynameisPhilip’
# Same as lists.
>>> ‘ ’.join([‘My’, ‘name’, ‘is’,
upper(), lower() and title() ‘Philip’])
>>> greet = ‘Hello world!’ # ‘My name is Philip’
>>> greet.upper()
# ‘HELLO WORLD!’ >>> ‘-’.join([‘My’, ‘name’, ‘is’,
‘Philip’])
>>> greet.lower() # ‘My-name-is-Philip’
# ‘hello world!’
split() - splits strings into a
>>> greet.title() list. By default it’ll use
# ‘Hello World!’ whitespace to separate the items.

isupper() and islower() methods >>> ‘My name is Philip’.split()


>>> spam = ‘Hello world!’ # [‘My’, ‘name’, ‘is’, ‘Philip’]
>>> spam.islower()
# False >>> ‘My-name-is-Philip’.split(‘-’)
# [‘My’, ‘name’, ‘is’, ‘Philip’]
>>> spam.isupper()
# False The count method
Counts the number of occurrences
>>> ‘HELLO’.isupper() of a given character or substring
# True in the string it is applied to.
Can be optionally provided with a
>>> ‘abc123’.islower() start and end index.
# True
>>> sentence = ‘one duck two duck
>>> ‘12345’.islower() three duck’
# False >>> sentence.count(‘duck’)
# 3
replace() method
>>> text = ‘Hello world!’
>>> text.replace(‘world’,
‘planet’)
# ‘Hello planet!’

f-strings
>>> name = ‘ELizabeth’
>>> f’Hello {name}!’
# ‘Hello Elizabeth’

You might also like