Introduction to Python - Lecture Notes

Jul 13, 2024

Python Course Introduction

Instructor: Mosh

Course Overview

  • Learn to program in Python from scratch
  • Python's popularity and usage areas:
    • Automation
    • Artificial Intelligence (AI)
    • Application and website development (e.g., Instagram, Dropbox)
  • Course structure:
    • Core Python concepts
    • Building three projects together:
      1. Website for grocery store (using Django)
      2. Machine learning (predicting music preferences)
      3. Automating repetitive tasks (processing spreadsheets)

Installation and Setup

Installing Python

  1. Go to Python.org and download the latest version (e.g., Python 3.7.2).
  2. Install Python:
    • Windows: Ensure Add Python to PATH is checked.
    • Mac: Follow installation wizard steps, agree to license, and install.

Installing PyCharm

  1. Go to JetBrains PyCharm.
  2. Download the Community Edition (free version).
  3. Install PyCharm:
    • Windows: Use installation wizard.
    • Mac: Drag and drop PyCharm to applications folder.
  4. Run PyCharm and create a new project named Hello World.
  5. Set Python interpreter to Python 3 (ensure path is correct).
  6. Create a new Python file: app.py.

Writing First Python Program

  1. Write and run the following code in app.py:
    print("Hi, I am Mosh Hamedani")
    
  2. Running the program:
    • Mac shortcut: Control + Option + R
    • Windows shortcut: Refer to PyCharm settings

Basic Python Concepts

Printing and Drawing Shapes

  • Drawing with print statements:
    print("O----")
    print(" ||||")
    print("*****")
    
  • Multiplication of strings:
    print("*" * 10)
    

Variables

  • Defining and using variables:
    price = 10
    rating = 4.9
    name = "Mosh"
    is_published = True
    
  • Types of values:
    • Integers (e.g., 10)
    • Floats (e.g., 4.9)
    • Strings (e.g., "Mosh")
    • Booleans (e.g., True)

Receiving Input

  • Using input() function:
    name = input('What is your name? ')
    print('Hi ' + name)
    
  • Combining strings with concatenation:
    color = input('What is your favorite color? ')
    print(name + ' likes ' + color)
    

Data Types and Conversions

  • Types of conversions:
    • String to Integer: int()
    • String to Float: float()
    • String to Boolean: bool()
    birth_year = int(input('Enter your birth year: '))
    age = 2023 - birth_year
    print('Your age is ' + str(age))
    

Formatted Strings

  • Creating formatted strings:
    first_name = "John"
    last_name = "Smith"
    msg = f'{first_name} [{last_name}] is a coder'
    print(msg)
    

Python String Methods

  • Common methods:
    • len(): Length of a string
    • upper(): Convert to uppercase
    • lower(): Convert to lowercase
    • find(): Return the index of the first occurrence
    • replace(): Replace substrings
    • in operator: Check existence
    course = 'Python for Beginners'
    print(course.upper())
    print(course.find('y'))
    print(course.replace('for', '4'))
    print('Python' in course)
    

Arithmetic Operations

  • Basic operations:
    print(10 + 3)
    print(10 - 3)
    print(10 * 3)
    print(10 / 3)  # returns float
    print(10 // 3) # returns int
    print(10 % 3)
    print(10 ** 3)
    
  • Augmented assignment operators:
    x = 10
    x += 3
    
  • Operator precedence:
    • Parentheses
    • Exponentiation
    • Multiplication/Division
    • Addition/Subtraction

Lists

  • Creating and manipulating lists:
    names = ['John', 'Bob', 'Mosh', 'Sarah', 'Mary']
    names[0] = 'Jon'
    print(names[0:3])
    
  • List methods:
    • append(): Add item to end
    • insert(): Add item at specific index
    • remove(): Remove item
    • clear(): Clear list
    • pop(): Remove last item
    • index(): Find index of item
    numbers = [1, 2, 3, 4, 5]
    numbers.append(6)
    numbers.insert(0, -1)
    numbers.remove(3)
    numbers.clear()
    numbers = [1, 2, 3, 4, 5]
    print(numbers.index(3))
    

Tuples

  • Tuples are immutable lists:
    numbers = (1, 2, 3)
    print(numbers[0])
    

Functions

  • Creating functions:
    def greet_user():
        print('Hi there!')
        print('Welcome aboard')
    greet_user()
    
  • Parameters and arguments:
    def greet_user(name):
        print(f'Hi {name}!')
    greet_user('John')
    
  • Keyword arguments and default parameters:
    def greet_user(first_name, last_name):
        print(f'Hi {first_name} {last_name}!')
    greet_user('John', last_name='Smith')
    

Error Handling

  • Using try-except blocks:
    try:
        age = int(input('Age: '))
        print(age)
    except ValueError:
        print('Invalid Value')
    
  • Catching different exceptions:
    try:
        age = int(input('Age: '))
        income = 20000
        risk = income / age
        print(age)
    except ZeroDivisionError:
        print('Age cannot be 0')
    except ValueError:
        print('Invalid Value')
    

Classes and Objects

Defining Classes and Creating Objects

  • Creating a class and using constructors:
    class Point:
        def __init__(self, x, y):
            self.x = x
            self.y = y
        def move(self):
            print('move')
        def draw(self):
            print('draw')
    point = Point(10, 20)
    point.draw()
    

Inheritance

  • Inheriting from other classes:
    class Mammal:
        def walk(self):
            print('walk')
    class Dog(Mammal):
        def bark(self):
            print('bark')
    dog1 = Dog()
    dog1.walk()
    dog1.bark()
    

Modules

  • Importing modules:
    import converters
    from converters import kg_to_lbs
    

Packages

  • Structuring code with packages:
    ecommerce/
        __init__.py
        shipping.py
    
    from ecommerce.shipping import calc_shipping
    

Random Module

  • Using the random module:
    import random
    print(random.random())
    print(random.randint(1, 10))
    

Working with Directories

  • Using Path from pathlib module:
    from pathlib import Path
    path = Path("ecommerce")
    print(path.exists())
    

Python Package Index (PyPI)

  • Installing packages:
    pip install openpyxl
    

Project: Automating Tasks (Spreadsheet Processing)

Using openpyxl

  • Reading and writing Excel files:
    import openpyxl as xl
    from openpyxl.chart import BarChart, Reference
    workbook = xl.load_workbook('transactions.xlsx')
    sheet = workbook['Sheet1']
    for row in range(2, sheet.max_row + 1):
        cell = sheet.cell(row, 3)
        corrected_price = cell.value * 0.9
        corrected_price_cell = sheet.cell(row, 4)
        corrected_price_cell.value = corrected_price
    values = Reference(sheet, min_row=2, max_row=sheet.max_row, min_col=4, max_col=4)
    chart = BarChart()
    chart.add_data(values)
    sheet.add_chart(chart, 'e2')
    workbook.save('transactions2.xlsx')
    

Machine Learning

Overview and Workflow

  • Steps in a machine learning project:
    1. Import data
    2. Clean data
    3. Split data into training and testing sets
    4. Create a model
    5. Train the model
    6. Make predictions
    7. Evaluate the model

Using pandas and scikit-learn

  • Loading a dataset with pandas:
    import pandas as pd
    df = pd.read_csv('music.csv')
    X = df.drop(columns=['genre'])
    y = df['genre']
    
  • Building and training a model:
    from sklearn.tree import DecisionTreeClassifier
    model = DecisionTreeClassifier()
    model.fit(X, y)
    predictions = model.predict([[21, 1], [22, 0]])
    print(predictions)
    
  • Measuring accuracy:
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import accuracy_score
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    model.fit(X_train, y_train)
    predictions = model.predict(X_test)
    score = accuracy_score(y_test, predictions)
    print(score)
    
  • Persisting models:
    import joblib
    joblib.dump(model, 'music-recommender.joblib')
    model = joblib.load('music-recommender.joblib')
    predictions = model.predict([[21, 1]])
    
  • Visualizing decision trees:
    from sklearn import tree
    tree.export_graphviz(model, out_file='music-recommender.dot',
                        feature_names=['age', 'gender'],
                        class_names=sorted(y.unique()),
                        label='all', rounded=True, filled=True)
    

Web Development with Django

Setting Up Django Project

  • Installing Django:
    pip install django==2.1
    
  • Creating a Django project:
    django-admin startproject pyshop .
    ```