Python Cheatsheet
Cheatsheet for Python syntax
Python Cheatsheet
Variables
Variable names use underscores between words for complex names
Spacing
Python enforces consistent tabbing. So, when you’re working with loops inside loops or functions inside classes, etc., you must preserve the hierarchy using meaningful whitespace.
if this_thing == True: print(“this!”)
for thing in many_things: if this_is == True: print(‘This!’) else: print(“This instead”)
Conditional Tests (if)
Place if
, elif
, and else
on separate lines. Each logic line must end in a colon, and the subsequent lines must be indented. You do not need to put an “end” keyword at the end of the sequence. In Python 3 you must indent with five spaces (though most text editors will do this for you).
Operators
Coming soon!
Method Calls
Parentheses are required (though will change in Python 2 vs 3). Additionally, if you you do not give parentheses at the end of a function it will not run.
Method Definitions
Methods can return values which can be assigned to a variable. The function must end with a return statement, something that signifies what the function is giving back when called.
Dictionaries
Dictionaries hold objects and are referenced by their key
assignment.
Lists
Lists hold objects and are referenced by their position, starting with
position 0
. You can use a ‘:’ to grab everything before or after particular index positions.
For Loops
Loops allow you to apply the same thing to each element in a list. You assign a variable name to refer to the item in each index position. The following both do the same thing.
List Comprehension
List comprehensions are a way of neatly organizing a particular loop type that happens often. These do the same thing.