Python cheat sheet

Unit 03: Data types

Data type Description Python example
integer whole numbers age=100
float numbers w/ decimals price=9.95
boolean true or false saved=True
string text, numbers, symbols, within double quotes name = "abc"

Unit 03: Declaring variables

The LHS (left-hand side) of the Assignment Operator ( = ) is the variable we are writing data to. The RHS (right-hand side) of the Assignment Operator ( = ) can be a literal (hard-coded data), another variable (to copy over), or an expression, such as a math operation.

Create integer Create string Create float Create boolean
my_number = 123 my_text = "Hello!" my_float = 9.99 my_question = True
Copy data from VAR2 to VAR1 Storing result of math operation Incrementing an int variable
VAR1 = VAR2 sum = num1 + num2 num = num + 1

Unit 03: Displaying output

Python uses the print function to display text to the screen. You can print out literals (hard-coded numbers, text, etc.), variable values, or a mix of both by separating each item with a comma ( , ).

Display "Hello!" Display contents of name variable Display "Name is", and then the name variable
print( "Hello!" ) print( name ) print( "Name is", name )

Unit 03: Getting input

Python uses the input function to (1) display a message to the user to ask them for information, and (2) gets input from the keyboard. All keyboard input must be stored back in a variable, otherwise the data disappears.

Ask user to enter their name, store in variable name
name = input( "Enter your name: " )

To get a float or integer input, you have to wrap the input function in int() or float():

Ask user to enter integer, store in num Ask the user to a float, store in price
num = int( input( "Enter a number: " ) ) price = float( input( "Enter a number: " ) )

Unit 05: Relational operators

Comparison Relational operator Example
Is a equal to b? == a == b
Is a not equal to b? != a != b
Is a greater than b? > a > b
Is a greater than or equal to b? >= a >= b
Is a less than b? < a < b
Is a less than or equal to b? <= a <= b

Unit 05: Logic operators

Logic operator True when… False when…
and All sub-condition are True At least one sub-condition is False
or At least one sub-condition is True All sub-conditions are False
not The sub-condition is False The sub-condition is True

Unit 05: Branching with if statements

An if statement asks a yes/no question - this is the CONDITION. A condition can be built from variables, literal values, relational operators, and logic operators.

The contents of the if statement - the code that gets executed if the condition is true - must be tabbed forward by 1. Once you un-indent that tab, you're then outside of the if statement.

If statement:

General form:

if ( CONDITION ):
    # Executes when CONDITION is True
    # Executes when CONDITION is True

# Outside of the if statement;
# executes no matter what

Example:

age = int( input( "Enter your age: " ) )
if ( age >= 18 ):
    print( "You can vote!" )

print( "Goodbye" )


If/else statement:

General form:

if ( CONDITION ):
    # Executes when CONDITION is True
    # Executes when CONDITION is True
else:
    # Executes when CONDITION is False
    # Executes when CONDITION is False

# Outside of the if statement;
# executes no matter what

Example:

if ( fuel < 50 ):
    print( "Low fuel!" )
else:
    print( "Doing OK on gas" )

print( "Goodbye" )

If/else if/else statement: Note that the "else" is optional here, but can be used as the default that gets executed if all if/elif conditions fail.

General form:

if ( CONDITION ):
    # Executes when CONDITION is True

elif ( CONDITION2 ):
    # Executes when CONDITION is False
    # and CONDITION2 is True

elif ( CONDITION3 ):
    # Executes when CONDITION is False
    # and CONDITION2 is False
    # and CONDITION3 is True

else:
    # Executes if all previous were False

# Outside of the if statement;
# executes no matter what

Example:

if ( score >= 90 ):
    print( "Grade: A" )

elif ( score >= 80 ):
    print( "Grade: B" )

elif ( score >= 70 ):
    print( "Grade: C" )

elif ( score >= 60 ):
    print( "Grade: D" )

else:
    print( "Grade: F" )

print( "Goodbye" )


Unit 06: Repeating with while loops

While loops also operate off CONDITIONS like if statements, but they will continue looping while the CONDITION evaluates to True.

General form:

while ( CONDITION ):
    # do stuff

Count up loop:

counter = 0
while ( counter < 10 ):
    print( counter )
    counter = counter + 1
 print( "Goodbye" )

Verify input loop:

min_num = 1
max_num = 10
choice = int( input( "Enter a number: " ) )

while ( choice < min_num || choice > max_num ):
    print( "Invalid selection! Try again!" )
    choice = int( input( "Enter a number: " ) )

print( "Thank you for your cooperation." )

Program loop:

running = True

while ( running ):
    print( "1. OptionA" )
    print( "2. Quit" )
    choice = int( input( "Choice: " ) )

    if ( choice == 2 ): # Quit
        running = False
    # end of if statement
# end of while loop

print( "Goodbye" )


Unit 07: Lists of data

Create an empty list Create a list of strings Create a list of floats
my_list = [] my_pets = [ "Kabe", "Luna" ] temps = [ 71.5, 80, 68.7 ]

An index is the position of an item in the list. For a list with 5 items in it, valid indices are 0 to 4. The data in the list at that position is called the element. It is basically one variable in the list of variables. Use the len() function to get the # of items stored in a list.

Access first item Access second item Access third item Print amount of items in list
print( my_pets[0] ) print( my_pets[1] ) print( my_pets[2] ) print( len( my_pets ) )

You can also store an index in an integer variable and access items that way.

index = int( input( "Who is your favorite student? " ) )
print( "Favorite student is:", studentList[index] )

To add additional information to the list, we use the append function:

Add a new string to a list Add a new float to a list
my_pets.append( "Luna" ) prices.append( 9.99 )

Unit 07: Iterating over lists

We can use a loop to iterate over all the elements in a list. With one loop, we can also access each element's index. With the other, we skip the index to have a nice simple loop and simple alias variable.

Loop with index: We have a counter variable i, and we can access an element by using the list's name (LISTNAME) and the subscript operator ([ ]) and the index i inside2

for i in range( len( LISTNAME ) ):
   # Display index (i) and
   # then the element (LISTNAME[i]):
   print( i, LISTNAME[i] )

Loop without index: Each loop, the element is stored in the temporary alias variable, ITEM (you can rename this to anything)

for ITEM in LISTNAME:
    print( ITEM )


Unit 09: Functions

Functions are a way to move code over. We can pass in input and retrieve output from it, though each of these are optional. Each design has different uses. Functions should be defined at the top of your code file.

General form:

def FUNCTIONNAME( VAR1, VAR2 ):
  return RETURNDATA

# Main program code (call function):
VARIABLENAME = FUNCTIONNAME( item1, item2 )

Example - Yes input / No output:

def Display( name, price ):
  print( "Product:", name, "Price: $", price )

# Main program code
product1name = "Burger";
product1price = 7.75

# Call function
Display( product1name, product1price )

Example - Yes input / Yes output:

def Add( num1, num2 ):
  return num1 + num2

# Main program code
number1 = int( input( "Enter first number: " ) )
number2 = int( input( "Enter second number: " ) )

# Call function, store RETURN value in result variable
result = Add( number1, number2 )
print( "Result is:", result )

Example - No input / No output:

def DisplayMainMenu():
  print( "1. Play game" )
  print( "2. Load game" )
  print( "3. Quit" )

# Main program code
# Call function
DisplayMainMenu()

Example - No input / Yes output:

def GetTax():
  return 0.091

# Main program code
price = float( input( "Enter price: " ) )

# Call function
tax = GetTax()

total_price = price + price * tax
print( "Total price: $", total_price )

Unit 10: Classes

Classes are a way we can make new data types. Our classes can contain functions and variables.

Generic form:

class CLASSNAME:              # Defining class
    def __init__( self ):
        self.STRINGVAR = ""   # Member variable

    void Display( self ):     # Member function
      print( self.STRINGVAR )

# Main program code
my_var = CLASSNAME()          # Creating variable
my_var.STRINGVAR = "Hello"    # Assign value to member variable
my_var.Display()              # Call member function

Example:

class Ingredient:              # Defining class
    def __init__(self):
        self.amount = 0        # Member variable
        self.name = ""         # Member variable
        self.unit = ""         # Member variable

    def Display( self ):       # Member function
        print( self.name, ":", self.amount, self.unit )

# Main program code
ingredient1 = Ingredient()     # Create new ingredient variable
ingredient1.name = "Butter"    # Assign value to member variables
ingredient1.amount = 1
ingredient1.unit = "Stick"
ingredient1.Display()          # Call member function

Author: RachelWil

Created: 2023-10-25 Wed 16:30

Validate