Académique Documents
Professionnel Documents
Culture Documents
PYTHON CHEAT
SHEET
VARIABLE AND STRINGS
• Variables are used to store values. A string is a series of characters, surrounded by single or double quotes.
Make a list
Syntax: Bikes = [“trek” , “redline” , “giant” ]
Get the first item in a list
Syntax: first_bike = bike[0]
Get the last item in a list
Syntax: first_bike = bike[-1]
LIST (CONT…) Making a numerical list
Syntax: squares = []
Looping through a list for x in range (1, 11):
Syntax: for bike in bikes:
print (bike)
squares.append(x**2)
List comprehensions
Syntax: squares = [x**2 for x in range (1,11)
Adding items to a list
Syntax: bikes = [] Slicing a list
bikes.append (“trek”) Syntax: finisher = [“sam”, “bob”, “ada”, “bea”]
bikes.append (“redline”) first_two = finisher [:2]
bikes.append (“giant”)
Copying a list
Syntax: copy_of_bikes = bike[:]
THE RANGE() FUNCTION
• You can use the range() function to work with a set of numbers efficiently.The range() function starts at 0
by default, and stops one number below the number passed to it.You can use the list() function to
efficiently generate a large list of numbers.
• list.append(elem) -- adds a single element to the end of the list. Common error: does not return the new list, just
modifies the original.
• list.insert(index, elem) -- inserts the element at the given index, shifting elements to the right.
• list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().
• list.index(elem) -- searches for the given element from the start of the list and returns its index. Throws a ValueError if
the element does not appear (use "in" to check without a ValueError).
• list.remove(elem) -- searches for the first instance of the given element and removes it (throws ValueError if not
present)
• list.sort() -- sorts the list in place (does not return it). (The sorted() function shown later is preferred.)
• list.reverse() -- reverses the list in place (does not return it)
• list.pop(index) -- removes and returns the element at the given index. Returns the rightmost element if index is
omitted (roughly the opposite of append()).
LIST LENGTH
• The len() function returns the number of items in a list.
Conditional tests
Conditional test with List
Equals x == 42
Not equal x != 42 Syntax: “trek” in bikes
Greater than x > 42
“surly” not in bikes
Greater than or equal to x >=42
Less than x < 42
Assigning Boolean values
Less than or equal to x <= 42
Syntax: game_active = True
can_edit = False
IF STATEMENTS (CONT…)
A simple if test
Syntax: if age > 18:
print(“ You can vote!”)
If-elif-else statment
Syntax: if age < 4:
ticket_price = 0
elif age < 18:
ticket_price = 10
else:
ticket_price = 15
USER INPUT
• Your programs can prompt the user for input
Counting to 5
Syntax: current_number = 1
while current_number <= 5:
print (current_number)
current_number += 1