Skip to content

Python Cheatsheet

Derek Graham edited this page Feb 23, 2018 · 2 revisions

Basic syntax clues for the most common scenarios in Python

Whitespace Matters !

Whitespace counts for more in Python than in many languages which use curly brackets to define blocks of code. Python uses indenting to decide which lines of code belong in a block and are associated with a condition, while, for loop, function body etc.

Comments

Comments start with a hash and affect the rest of the line

# this is a cool piece of code !

Strings

# create and assign
greeting = 'hello world'

# or 
greeting = "hello world"

Concatenation

full_path = folder + "\" + file_name

Numbers

house_number = 25
weight = 17.9

Booleans

True 

False

Lists

words = [ 'the', 'quick', 'brown', 'fox' ]
first = words[0]
last = words[-1]

Iteration

for word in words:
    print(word)
    

Append

words = []

words.append('the')
words.append('cat')
words.append('sat')

Comparsions


==
!=
>
<
>=
<=

Conditions

If

If must be followed by a colon. Code belonging to the if must be indented below it. You will get an error if the indent is too big or too small or inconsistent.

if name == 'bob':
    print('hi bob!')
    
if 'fox' in words:
    print('found a fox')

Else and Else If conditions are allowed but not Else If is elif. Multiple conditions can be joined together in an if using and & or keywords.

Console

Output

print('hello, world')

or

print("hello, world")

Input

Python 2

answer = raw_input('tell me your name ?')

Python 3

answer = input('tell me your name ?')

Iteration

While

# forever...
while True:
    print('everything is awesome')
    

Break and Continue are available and work as expected.

For

# numbers 0..100
for number in range(101):
    print(str(number))
    
# numbers 1..100
for number in range(1, 101):
    print(str(number))
    
# numbers 3,4,5,6,7
for number in range(3, 8):
    print(str(number))
    

Functions

No arguments

def say_something():
  print('hello')

Arguments

def say_something(message):
  print(message)

Returning a Value

def make_full_name(first_name, last_name):
  return first_name + " " + last_name
  

Scope and Globals

Because variables are created when first mentioned, it can be difficult to decide (and hint to python) between a variable in a function scope or at the global scope.

name = 'jake'

def print_name():
    print(name)    # Not assigning so don't need 'global'

def change_name(new_name):
    global name    # hint we are now talking about global variable
    name = new_name

print_name()
change_name('finn')
print_name()  

Classes

Definition

class Dog():
 
 def __init__(self, name):
    self.name = name
    
 def sit(self):
    print(name + ' is sitting')
    return True

 def speak(self):
    print(name + ' says woof')
    
 def rate(self):
    print('13/10')
    

Instantiation

my_dog = Dog('Inca')
your_dog = Dog('Rover')

my_dog.sit()
your_dog.speak()

Clone this wiki locally