Python basics - cheatsheet

Basics

Variables

  • assign

    1
    2
    message = "Hello world"
    print(message)
  • concatenantion

    1
    2
    3
    full_name ="First name: {}\nLastname: {} ".format(
    first_name,
    last_name)

User input

  • Strings

    1
    2
    3
    # default is string
    name = input("What's your name? ")
    print("Hello, " + name + "!")
  • Numbers

    1
    2
    3
    4
    age = input("How old are you? ")
    age = int(age)
    pi = input("What's the value of pi? ")
    pi = float(pi)

Lists

  • definition

    1
    2
    3
    4
    # assign
    bikes = ["mountain bike", "aegean blue"]
    # clone a list
    copy_of_bikes = bikes[:]
  • get item

    1
    2
    3
    4
    # get first
    first_bike = bikes[0]
    # get last
    last_bike = bikes[-1]
  • add and remove items

    1
    2
    3
    4
    bikes = []
    bikes.append("mountain bike")
    bikes.append("aegean blue")
    bikes.remove("aegean blue")
  • List comprehensions

    1
    double_values = [x*2 for x in range(1, 11)]
  • Slicing a list

    1
    2
    finishers = ["Ada", "Bob", "Charles"]
    first_two = finishers[:2]

Tuples

  • Non-editable lists
    1
    definition = (1366, 768)

Dictionaries

  • Key-value pairs items

    1
    2
    3
    4
    5
    6
    alien = {
    'color': 'green',
    'points': 2
    }

    print("The alien's color is " + alien['color'])
  • Adding a new key-value pair

    1
    alien['x_position'] = 0
  • Looping on dictionaries

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    # loop on pairs
    fav_numbers = {'eric': 17, 'ever': 4}
    for name, number in fav_numbers.items():
    print(name + ' loves ' + str(number))

    # loop on keys
    fav_numbers = {'eric': 17, 'ever': 4}
    for name in fav_numbers.keys():
    print(name + ' loves a number')

    # loop on values
    fav_numbers = {'eric': 17, 'ever': 4}
    for number in fav_numbers.values():
    print(str(number) + ' is a favorite')

Control structures

Conditionals

  • Conditional tests

    Condition Representation
    equals x == 42
    not equals x != 42
    greater than x > 42
    greater or equal to x >= 42
    less than x< 42
    less or equal to x <= 42
  • Conditional test with lists

    1
    2
    'mountain bike' in bikes
    'car' not in bikes
  • Conditional blocks

    1
    2
    3
    4
    5
    6
    if age < 4:
    ticket_price = 0
    elif age < 18:
    ticket_price = 10
    else:
    ticket_price = 15

Loops

  • Conditional block
    1
    2
    3
    4
    current_value = 1
    while current_value <= 5:
    print(current_value)
    current_value += 1

Files

  • Read

    1
    2
    3
    4
    5
    file_name = 'demofile.txt'
    with open(file_name) as file_object:
    lines = file_object.readlines()
    for line in lines:
    print(line)
  • Write

    1
    2
    3
    4
    5
    6
    7
    8
    # overwrite
    file_name = 'journal.txt'
    with open(file_name, 'w') as file_object:
    file_object.write("I am coding Python.")
    # append
    filename = 'journal.txt'
    with open(filename, 'a') as file_object:
    file_object.write("\nThis is some appended text.")

Functions

  • Simple

    1
    2
    3
    4
    5
    6
    7
    # defintion
    def greet_user():
    # Display a simple greeting
    print("Hello!")

    # call
    greet_user()
  • With default value parameters

    1
    2
    3
    4
    5
    6
    def make_pizza(topping='bacon'):
    """Make a single-topping pizza."""
    print("Have a " + topping + " pizza!")

    make_pizza()
    make_pizza('pepperoni')
  • Returning a value

    1
    2
    3
    4
    def add_numbers(x, y):
    """Add two numbers and return the sum.""" return x + y

    sum = add_numbers(3, 5) print(sum)

Classes

  • Simple class

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class Dog():
    """Represent a dog."""
    def __init__(self, name):
    """Initialize dog object."""
    self.name = name
    def sit(self):
    """Simulate sitting."""
    print(self.name + " is sitting.")

    my_dog = Dog('Buddy')

    print(my_dog.name + " is a great dog!")
    my_dog.sit()
  • Inheritance

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    class SARDog(Dog):
    """Represent a search dog."""

    def __init__(self, name):
    """Initialize the sardog."""
    super().__init__(name)

    def search(self):
    """Simulate searching."""
    print(self.name + " is searching.")

    my_dog = SARDog('WToby')
    print(my_dog.name + " is a search dog.")
    my_dog.sit()
    my_dog.search()

Exceptions

  • Try/catch/else:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    prompt = "How many tickets do you need? "
    num_tickets = input(prompt)

    try:
    num_tickets = int(num_tickets)
    except ValueError:
    print("Please try again.")
    else:
    print("Your tickets are printing.")