Intro to Computer Science

Python Cheat Sheet

Variables

Store a value now, use it later.

The four kinds of value

Python figures out the kind for you. You just pick a name and use =.

Text (str)

Anything inside quotes.

name = "Steve"
print(name)
Output
Steve

Whole number (int)

No decimal point.

age = 24
print(age)
Output
24

Decimal number (float)

Has a decimal point.

angle = 31.8
print(angle)
Output
31.8

True or False (bool)

Only two options. Both start with a capital letter.

is_raining = True
print(is_raining)
Output
True

Doing math

SymbolWhat it doesExample
+Add7 + 2 gives 9
-Subtract7 - 2 gives 5
*Multiply7 * 2 gives 14
/Divide, always gives a decimal7 / 2 gives 3.5
//Divide and drop the decimal7 // 2 gives 3
%Remainder after dividing7 % 2 gives 1
**Raise to a power7 ** 2 gives 49

Changing capitalization

These hand back a new piece of text. The variable itself does not change unless you store the result.

MethodWhat it doesExample
.upper()Every letter capital"becca".upper() gives "BECCA"
.lower()Every letter lowercase"BECCA".lower() gives "becca"
.capitalize()First letter capital, the rest lowercase"bECCA".capitalize() gives "Becca"

Make it all capitals

.upper() shouts the whole thing.

name = "becca"
print(name.upper())
Output
BECCA

Make it all lowercase

.lower() is the one you reach for most, because it makes two pieces of text easy to compare.

name = "BECCA"
print(name.lower())
Output
becca

Capitalize the first letter

.capitalize() also lowercases everything after the first letter.

name = "bECCA"
print(name.capitalize())
Output
Becca

Keep the new version

Use this one

Store the result in a variable, or use it right where you need it.

name = "becca"
loud = name.upper()
print(loud)
Output
BECCA

Forgetting to store it

Common mistake

name.upper() on its own throws the new text away. name is still the way it was.

name = "becca"
name.upper()
print(name)
Output
becca

Comments

Leave a note with #

Start the line with # and Python ignores it.

# This line is a note for humans. Python skips it.
score = 0
print(score)
Output
0