Show Menu
Cheatography

Python Basics Cheat Sheet (DRAFT) by

Basic Python syntax reference sheet (for CSC-121 at CPCC)

This is a draft cheat sheet. It is a work in progress and is not finished yet.

print Function & Formatting

Syntax
Explan­ation
print(­'Hello Johnny.')
Print string as output
print(­'Hello\nJohnny.')
Print "­Joh­nny." on a new line
print(f'Hello {name}.')
[F-string] Allows inserting variables & expres­sions.
print(­f'{­payment:.2f}')
[Precision design­ator] Value is rounded to 2 decimal places in output & displayed as floati­ng-­point number.
print(­f'{­number:.2e}')
Value is rounded to 2 decimal places in output & displayed in scientific notation.
print(­f'{­number:,}')
[Comma separator] Displays commas in large numbers (e.g. "­10,­000­").
print(­f'{­dis­count:.0%}')
Converts decimal to percent in output.
print(­f'{­number:10}')
Sets minimum field width of 10.
print(­f'{­number:^}')
< = left align
> = right align
^ = center align
num = 12345.6789

print(­f'Num is {num:>­10,.2f}')
Example with all designators.
Output:
Num is  12,345.68
Order of format designators:
variable:[alignment][width][,][.precision][type]

if Statements

if condition

Loops

############################################################
# while: for condition-controlled loops,
#   & count-controlled loops (w/ added steps)

# Basic while loop:
while n < 5:
    print('Value is less than 5')
    n += 1

# Count-controlled while loop:
n = 0          #Initialization
while n < 5:   #Comparison
    print('Value is less than 5')
    n += 1    #Update

############################################################
# for: for count-controlled loops & sequences of data
#   (with or without "range")

for variable in [value1, value2, etc]:
    Statements

for variable in range(x, y, z):
    Statements   #Range: x=start, y=end, z=step value

############################################################
# else clause: (optional) for loops that 
#   contain a break statement

# Else clause never executes because break does execute:
for n in range(10):
    if n == 5:
        print('Breaking out of loop')
        break
    print(n)
else:
    print(f'After the loop, n is {n}.')

# Else clause does execute because break never does:
for n in range(3):
    if n == 5:
        print('Breaking out of loop')
        break
    print(n)
else:
    print(f'After the loop, n is {n}.')
 

Variables

Assign and return variable's value:
(walrus operator)
print(variable := value)
Set variable from input:
variable = input(prompt)
Set integer variable
variable = int(expression)
Set float variable:
(decimal number)
variable = float(expression)
Set string variable from input:
variable = str(input(prompt))
Set Boolean variable:
(true/false)
Single Line:
variable = val1 if condition else val2

Multiple Lines:
if condition:

_ _ variable = val1

else

_ _ variable = val2

String concat­ena­tion:
message = 'Hello ' + 'world'

print(­mes­sage)

Output:
Hello world

Boolean Expres­sions

x > y
x is greater than y
x < y
x is less than y
x >= y
x is greater than or equal to y
x <= y
x is less than or equal to y
x == y
x is equal to y
x != y
x is not equal to y
[expres­sion1] and [expres­sion2]
both expres­sions must be true
[expres­sion1] or [expres­sion2]
at least one expression must be true
not [expression]
reverses value (false­=true, true=f­alse)

Turtle Art!

Command
What It Does
import turtle
Necessary at start of program
turtle.done()
Put at very end of program (keeps window from auto-c­losing)
 
--- Colors & Sizes ---
turtle.setup(width, height)
Set window size (in pixels)
turtle.bg­color('color')
Set window background color
turtle.pe­nsize(width)
Set pen thickness (in pixels)
turtle.pe­nco­lor('color')
Set pen color
 
--- Turtle Management ---
turtle.pe­nup()
Raise pen (to move without drawing)
turtle.pe­ndown()
Lower pen (to resume drawing)
turtle.hi­det­urtle()
Hides turtle (does not affect drawing)
turtle.sh­owt­urtle()
Displays turtle
 
--- Input via Dialog Box ---
var = turtle.textinput ('title', 'prompt')
Assigns user's input to the variable as a string
var = turtle.nu­minput ('title', 'prompt')
Assigns user's input to the variable as a float
var = turtle.nu­minput ('t', 'p', default=x,
minval=
y, maxval=z)
Optional arguments:
x = default value displayed in input box
y = reject any number less than y
z = reject any number greater than z
 
--- Movement & Positi­oning ---
turtle.fo­rward(n)
moves turtle n distance in direction it's currently facing
turtle.se­the­ading(n)
Set turtle's heading to a specific angle (90 is up)
turtle.right(n)
Turn n degrees to the right
turtle.left(n)
Turn n degrees to the left
turtle.goto(x, y)
Move turtle to specific coordi­nates
turtle.pos()
Displays turtle's current coordi­nates
 
--- Drawing & Writing ---
turtle.fi­llc­olor('color')
Set color for filling shape
turtle.be­gin­_fill()
Use before drawing shape to be filled
turtle.en­d_f­ill()
Use after shape has been drawn
turtle.ci­rcle(radius)
Draw a circle with specified radius
turtle.dot()
Draw a simple dot at current location
turtle.write(text)
Writes text, with lower left corner of 1st character at turtle's coordi­nates
 
--- Erasing & Undoing ---
turtle.cl­ear()
Erases all drawing, but doesn't reset turtle position, pen color, or background color
turtle.re­set()
Clears­/resets everything except window background color
turtle.cl­ear­scr­een()
Clears­/resets everything