Skip to content
Introduction to Python
  • AI Chat
  • Code
  • Report
  • Introduction to Python

    Run the hidden code cell below to import the data used in this course.

    Take Notes

    Add notes about the concepts you've learned and code cells with code you want to keep.

    Add your notes here

    # Add your code snippets here

    Explore Datasets

    Use the arrays imported in the first cell to explore the data and practice your skills!

    • Print out the weight of the first ten baseball players.
    • What is the median weight of all baseball players in the data?
    • Print out the names of all players with a height greater than 80 (heights are in inches).
    • Who is taller on average? Baseball players or soccer players? Keep in mind that baseball heights are stored in inches!
    • The values in soccer_shooting are decimals. Convert them to whole numbers (e.g., 0.98 becomes 98).
    • Do taller players get higher ratings? Calculate the correlation between soccer_ratings and soccer_heights to find out!
    • What is the average rating for attacking players ('A')?

    Python Cheat Sheet

    COMMENTS

    Single line comments start with a '#'. Only the line with the '#' is considered as a comment.

    This is a comment

    ''' Multiline comments are encased between triple quotes. Everything within the triple quotes is considered a comment. This is a multiline comment. '''

    VARIABLES AND DATA TYPES

    x = 5 # Integer: Whole numbers y = 5.0 # Float: Decimal numbers z = 'Hello' # String: Text b = True # Boolean: True or False values t = (1, 2, 3) # Tuple: Immutable sequence of values s = {1, 2, 3} # Set: Unordered collection of unique values

    Type Conversion

    a = str(x) # Converts x to string c = int(y) # Converts y to integer d = float(x) # Converts x to float

    LISTS

    List: Ordered collection of values

    list1 = [1, 2, 3, 4, 5]

    List Operations

    len(list1) # Returns the length of list list1.append(6) # Appends 6 to end of list list1.insert(0, 0) # Inserts 0 at index 0 list1.remove(0) # Removes the first occurrence of 0 from the list list1.pop(0) # Removes and returns the element at index 0

    TUPLES

    Tuples are like lists, but they are immutable - their values can't be changed

    tuple1 = (1, 2, 3)

    SETS

    Sets are unordered collections of unique elements

    set1 = {1, 2, 3} set1.add(4) # Adds 4 to the set set1.remove(1) # Removes 1 from the set

    STRINGS

    s = 'Hello, World!'

    String Operations

    s[0] # Accesses first character of string s[1:5] # Slices string from index 1 to 4 (end index is exclusive)

    DICTIONARIES

    Dictionary: Collection of key-value pairs

    dict1 = {'key1': 'value1', 'key2': 'value2'}

    Dictionary Operations

    dict1.get('key1') # Returns value for 'key1', or None if 'key1' is not present

    CONDITIONALS

    Used to perform different actions based on different conditions

    if x < y: print("x is less than y") elif x > y: print("x is greater than y") else: print("x is equal to y")

    LOOPS

    For and While loops are used to iterate over a sequence (like a list, tuple, dictionary, set, or string) or perform a task multiple times

    for i in list1: print(i) # Prints all elements in list1

    for i in range(10): # Prints 0 through 9 print(i)

    while x < 10: print(x) x += 1

    List Comprehensions

    List comprehensions provide a concise way to create lists based on existing lists

    list2 = [i**2 for i in range(10)] # List of squares from 0 to 81

    FUNCTIONS

    Functions are blocks of code that only run when they are called

    def add(a, b): return a + b

    LAMBDA FUNCTIONS

    Lambda functions are anonymous functions that are declared with the lambda keyword

    add_lambda = lambda a, b: a + b # Equivalent to add function

    CLASSES AND OBJECTS

    Classes are user-defined data structures consisting of methods and attributes. Objects are instances of classes.

    class MyClass: def init(self, a): self.a = a

    def display(self): print(self.a)

    obj = MyClass(5) obj.display() # Prints: 5

    MODULES

    Modules are Python .py files that consist of Python code. They can define functions, classes, and variables that you can reference in other Python .py files.

    import math print(math.pi) # Prints: 3.141592653589793

    EXCEPTION HANDLING

    Exception handling is used to handle runtime errors that can occur in a program, to avoid program crashes and to provide meaningful error messages.

    try: print(1/0) except ZeroDivisionError as e: print(e)

    FILE I/O

    Python provides functions to handle file I/O (Input/Output) operations

    with open('filename.txt', 'r') as f: content = f.read() # Reads content from file

    Python Mini Cheat Sheet: Array Indexing & Variable Definition

    VARIABLE DEFINITION

    # A variable must be defined before it can be used. Defining a variable means assigning it a value. # Here's how to define a variable: ages = [25, 30, 35] # This is a list. Each element represents a person's age.

    NUMPY ARRAYS

    # Numpy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, # along with a large collection of high-level mathematical functions to operate on these arrays. # Before you use numpy, you have to import it: import numpy as np # Convert the ages list to a numpy array np_ages = np.array(ages) # Now you can perform operations on this numpy array discount_eligible = np_ages > 30 # Checks if each person is older than 30

    ARRAY INDEXING

    # In Python, you can access elements of a list or array using square brackets. # You put the index of the element you want inside the square brackets. # For example, to print the first element of np_ages, you would do: print(np_ages[0]) # You can also use arrays to index other arrays. # 'discount_eligible' is a boolean array that is True for each person older than 30, and False otherwise: # Now, you can use the 'discount_eligible' array to index the 'np_ages' array. # This will give you only the elements of 'np_ages' where 'discount_eligible' is True: print(np_ages[discount_eligible]) # This will print the ages of people who are older than 30