Python “Cheatsheet”
This page outlines most of the symbols, functions, structures, and libraries we use in Intro to Python.
Jump To
Symbols and Characters
Symbol | Name | Use(s) |
' or " |
quotes | hold strings |
''' or """ |
triple quotes | hold multi-line strings (aka literals), comment out multiple lines of code |
, |
comma | separates items in lists |
: |
colon | goes at the end of lines starting with def , if , for , while , etc.—indicates that next line will be indented |
# |
hash, hash mark, hashtag | comments out a single line of code |
() |
parentheses, round brackets | after functions, hold function parameters |
[] |
square brackets | hold lists, used for indexing |
{} |
braces, curly brackets, squiggly brackets | hold dictionaries |
= |
equals sign | assign a value to a variable |
== |
double equals | check whether two values are equal |
_ |
underscore | used (rarely) in variable names as a space |
Basic Functions
Print statements
print()
Program output:
(blank line)
print('Hello, world!')
print(17)
print([5, 8, 13])
Program output:
Hello, world!
17
[5, 8, 13]
print('My first sentence.', end=' ')
print('My second sentence.')
Program output:
My first sentence. My second sentence.
Input statements
name = input('What is your name? ')
name
is a variable that will save the inputinput()
waits for the user to hit Enter, then returns everything typed before that'What is your name? '
is a prompt for the user
Range function
range(5) # produces 0, 1, 2, 3, 4
range(6, 11) # produces 6, 7, 8, 9, 10
Conditionals
if
age = 37
if age > 18:
print('Please go vote!')
Program output:
Please go vote!
if
+ elif
secretNumber = 17
guess = 23
if guess < secretNumber:
print('Too low!')
elif guess > secretNumber:
print('Too high!')
Program output:
Too high!
if
+ elif
+ else
roll = random.randrange(1,7)
if roll == 1:
print('Advance 1 space.')
elif roll < 5:
print('Advance 2 spaces.')
else:
print('Advance 1 space and roll again.')
Program output:
(assume randrange
returned a 5)
Advance 1 space and roll again.
Comparison statements
-
A == B
checks if A and B are equalA < B
checks if A is less than B, and<=
checks if A is less than or equal to BA > B
andA >= B
check if A is greater than B, or greater than or equal to BA in B
can check a list B for an item A, or check a string B for a character or substring A
Loops
while
loops repeat under certain conditions (using similar comparison statements as conditionals)for
loops repeat for a certain set of things—usually using a string or a list
While loops
beat = 1
while beat <= 4:
print(str(beat) + '-ee-and-uh')
beat += 1
Program output:
1-ee-and-uh
2-ee-and-uh
3-ee-and-uh
4-ee-and-uh
In this loop, beat
is the sentinel variable. Notice that beat
was defined on the first line, was part of the looping condition, and got modified in the body of the loop. Those are all necessary features of a sentinel variable!
For loops
for letter in 'haberdashery':
print(letter + '~', end='')
Program output:
h~a~b~e~r~d~a~s~h~e~r~y~
animals = ['zebra', 'yeti', 'X-ray fish', 'wildebeest', 'viper']
for animal in animals:
print(animal[0].upper(), 'is for', animal)
Program output:
Z is for zebra
Y is for yeti
X is for X-ray fish
W is for wildebeest
V is for viper
for x in range(10):
print(x**2, end=' ')
Program output:
0 1 4 9 16 25 36 49 64 81
Functions
Functions can be used to store blocks of code that you want to use repeatedly. Unlike loops, functions can be reused at any time and in any order.
Defining a function
def interruptingFrog():
print('rrribbit!')
The def
tells Python that you are defining a new function named interruptingFrog()
. The empty parentheses are important (and they won’t always be empty!). Anything indented below that def
line will be considered part of the function.
Calling a function
interruptingFrog()
Program output:
rrribbit!
Function input
def multiply(n1, n2):
product = n1 * n2
print(product)
multiply(5, 7)
Program output:
35
n1
andn2
are parameters- when you call
multiply
, it requires two inputs
Function output
def getDirection():
directions = ['N', 'S', 'E', 'W']
direct = input('What direction do you want to go? ')
while True:
if direct not in directions:
direct = input('Please enter N, S, E, or W: ')
else:
return direct
return
outputs to the program (invisible), whereprint
outputs to the console (visible)return
can break out of an otherwise infinite loop!
Lists
soup = ['bean chili', 'clam chowder', 'French onion soup',
'butternut squash bisque']
print('gazpacho' in soup)
Program output:
False
for s in soup:
print('Yum, a nice hot bowl of ' + s + '!')
Program output:
Yum, a nice hot bowl of bean chili!
Yum, a nice hot bowl of clam chowder!
Yum, a nice hot bowl of French onion soup!
Yum, a nice hot bowl of butternut squash bisque!
print(soup[1])
Program output:
clam chowder
(Remember that indexing starts at 0.)
Dictionaries
MAwinter = {'October': 'cold and windy and rainy',
'November': 'cold and windy',
'December': 'cold and hopefully snowy',
'January': 'just cold',
'February': 'extra cold and windy',
'March': 'cold and snowy'}
print(MAwinter['January'])
Program output:
just cold
(Use keys to access values.)
mon = 'March'
if mon in MAwinter:
print(MAwinter[mon])
Program output:
cold and snowy
for month in MAwinter:
print('In ' + month + ', the weather is ' + MAwinter[month] + '.')
Program output:
In October, the weather is cold and windy and rainy.
In November, the weather is cold and windy.
In December, the weather is cold and hopefully snowy.
In January, the weather is just cold.
In February, the weather is extra cold and windy.
In March, the weather is cold and snowy.
Libraries
random
Provides functions for randomness.
randrange()
takes the same parameters asrange()
but returns a single random value from the rangerandint()
takes two parameters, a min and a max, and returns a random integer between min and max (inclusive)
termcolor
Offers color and formatting capabilities for printing to the console. Check out my demonstration of termcolor
.