A cheat sheet for the basic syntax and constructs of Python 3. It includes basic IO, conditionals, collections, functions, classes, modules and packages.

Syntax

  • Python uses indentation to mark code blocks

Basic IO

  • input() and output() functions are used to handle basic IO (input and output)
  • String interpolation: add f before string opening quote and surround a variable or an expression with curly brackets {}
    name = input("Hello World! What is your name?\n")
    welcome_message = f"Hello, {name} !"
    print(welcome_message)
    

Basic Types

Numeric types

  • We have our usual suspect operators +, -, *, / and %. We use ** for exponents
  • We have some basic functions to apply on numbers abs, round. However, if we want to go fancy, we can import the math module

Boolean

  • Logical Operators and, or and not
  • Comparison Operators ==, !=, <, >, <= and >=

String

  • We can use either Single quote ' or double quotes " to surround a string literals.
  • We use triple single quotes ''' or double quotes """ for multiline strings
import datetime
birth_year = input("What is your birth year?\n")
now = datetime.datetime.now()
age = int(now.year) - int(birth_year)
age_message = f"You are, {age}  years old!"
print(age_message)

Useful String Methods

  • Case manipulation: upper(), lower(), title()`
  • Finding index: find() which returns -1 if element is not found

Conditionals

if Statment

temperature = int(input("What is the temperature today?\n"))
if temperature < 15:
    print("It is freezing")
elif temperature > 25:
    print("It is getting hot in here")
else:
    print("Awesome")

Loops

While

i = 0
while i < 2:
    print(i)
    i += 1

For

for element in [1, 2]:
    print(element)

loop keywords

  • break

Collections

Ranges

  • We create a range using range() function
    • range(stop) creates a range from zero to the number stop, excluding the stop number
    • range(start, stop, step) creates a range from start to stop, excluding stop. step will be 1 if omitted

Lists

  • Create a list using square brackets l = ["a", "b", "c"]
  • access elements of the list by supplying index to square brackets a = l[0]
  • We can use negative index to access the elements counting from the end, d = l[-1]
  • we can use sequence operations to get a sub-list
    • ab = l[0:2] a list includes all the elements from index 0 to 1, the result doesn’t include the closing index
    • ab = l[:2] The start index can be omitted
    • cd = l[1:] The end index can be omitted
    • ab = l[:-1] We can still use negative values for index, note that the value at the last index will still be excluded
  • To check if an item exists in a collection, we can use the keyword in which returns a boolean. 1 in [1, 2, 3] will result in true
  • Useful functions
    • len() find list length
  • Useful methods
    • index(item), which will show error if the item doesn’t exist
    • append(item), insert(index, item)
    • remove(item), clear()
    • pop()
    • sort()
    • reverse()
    • copy()

      Unpacking Lists

      x, y, z = [1, 2, 3]
      

Tuples

  • Tuples are immutable
  • We use parenthesis () to define a new tuple
  • We can access items via square brackets the same way we did for lists

Unpacking Tuples

x, y, z = (1, 2, 3)

Dictionaries (Maps)

  • We use curly braces {} to define a dictionary {"a": a, "b":b}
  • We get the value using square brackets [] that is d["a"], which will return an error if the key doesn’t exist
  • We can use the get(key) method, which will return None if the key doesn’t exist. None is an object that represents the absence of a value
  • get(key, default) will return the default value if a value doesn’t exist

Useful methods

  • values() return a list of the values in the dictionary. Useful for iterating over the dictionary values
  • items() return a list of tuples, each of which is one of the key-value pairs in the dictionary keys and values

Functions

  • Functions must be declared before the scope in which they are used
  • def is the keyword to define a function
    def calculate_age(birth_year):
      now = datetime.datetime.now()
      return calculate_years_between(now.year, birth_year)
    
  • A function will return None if no return is present

Parameters

Let’s look at this example

def concatenate(s1, s2=""):
    return s1 + s2
  • The function concatenate has two parameters s1 and s2
  • s2 has a default value of an empty string. We can apply this function concatenate("hello") and it would not complain of a missing argument.
  • Parameters that have default values must come after those that do not have default parameters
  • We can use keyword arguments and not care for the order of the parameters (as compared to positional arguments) concatenate(s2="world", s1="hello)
  • Keyword arguments must come after positional arguments

    Variadic Parameters

  • A variadic parameter is a parameter that may map to one or more arguments
  • We add an * before the argument name to indicate a variadic parameter def myFun(*argv):
    def concatenate(*strings):
      result = ""
      for string in strings:
          result += string
      return result
    
  • We can call the concatenate method mentioned above, with any number of arguments, and those arguments would be bound to the list strings: concatenate("a", "b", "c")

Variadic Keyword Parameters

  • We prefix the parameter name with ** to indicate that it is variadic keyword parameter.
  • We can bind any number of named arguments, or key-value pairs of arguments to a keyword parameter
    def concatenate(**kwargs):
      return kwargs["s1"] + kwargs["s2"]
    print(concatenate(s1="a", s2="b"))  # prints `ab`
    
  • The same function could have been written as
    def concatenate(**kwargs):
      result = ""
      for value in kwargs.values():
          result += value
      return result
    

Classes

Class Declaration

class User:
    def __init__(self, name, year_of_birth):
        self.name = name
        self.year_of_birth = year_of_birth

    def age(self):
        now = datetime.datetime.now()
        return int(now.year) - int(self.year_of_birth)

Object Instantiation

name = input("Hello! What is your name?\n")
year_of_birth = input("What is your birth year?\n")
user = User(name, year_of_birth)

welcome_message = f"Hello, {user.name} !"
age_message = f"You are, {user.age()}  years old!"

Modules and Packages

  • A module is represented by a file
  • A package is represented by a directory with a special __init__.py file in it. That file can be empty
  • Logically, packages contain modules
  • We use import to import modules which may be in the same or in another package
    • We can import the whole module via import package_name.module_name, in that case we will need to use the fully qualified name to call any construct imported from that module package_name.module_name.function_name() for example
    • We can import specific construct form a module from package_name.module_name import some_construct. Here we can call the construct directly without needing to qualify it

Resources