Python Programming Course Lecture Notes

Jul 8, 2024

Python Programming Course

Introduction to Python

  • Python is a popular programming language sought after for jobs.
  • Beginner-friendly and easy to learn with very little syntax.
  • Suitable for automating tasks, scripting, and more.

Getting Started

  • Installing Python: Visit python.org/downloads. Choose Python 3.
  • Choosing a Text Editor: Recommended IDE is PyCharm from JetBrains.

Python Basics

  • First Program: Printing "Hello World"
print("Hello World")
  • Variables and Data Types: Strings, integers, booleans
    • Example: character_name = "John"

Control Structures

If Statements

  • Basic Structure:
if condition:
    # code
else:
    # code
  • Comparison Operators: ==, !=, >, <, >=, <=
  • Logical Operators: or, and, not

While Loops

  • Basic Structure:
while condition:
    # code
  • Example of looping through conditions

For Loops

  • Used to iterate over sequences (like lists or strings)
for element in sequence:
    # code

Functions

  • Defining Functions:
def function_name(parameters):
    # code
  • Return Statements: Used to return a value from a function

Working with Strings

  • String Methods: .upper(), .lower(), .isupper(), .islower(), .index(), .replace()
phrase = "Hello"
print(phrase.upper()) # Output: HELLO

Working with Lists

  • Basic Structure:
list_name = [item1, item2, item3]
  • List Methods: .append(), .insert(), .remove(), .clear(), .pop(), .sort(), .reverse(), .copy()

Tuples

  • Defining Tuples (immutable lists)
tuple_name = (item1, item2)

Exception Handling

  • Try-Except Block: To handle potential errors
try:
    # code
except Exception as e:
    # code

Reading and Writing Files

  • Open File: Modes r, w, a, r+
file = open('filename.txt', 'r')
content = file.read()
file.close()
  • Writing/Appending to File:
file = open('filename.txt', 'a')
file.write('add this text')
file.close()

Modules

  • Importing Modules: Import custom or built-in modules
import module_name
from module_name import specific_function
  • Using Pip: Install external modules
pip install module_name

Classes and Objects

  • Defining Classes:
class ClassName:
    def __init__(self, attr1, attr2):
        self.attr1 = attr1
        self.attr2 = attr2
  • Creating Objects:
object_name = ClassName(attr1, attr2)

Advanced Topics

Inheritance

  • Inheriting Classes:
class SubClass(SuperClass):
    # Additional or overridden methods

Functions in Classes

  • Defining Methods within Classes to modify or retrieve object data.

Using the Python Interpreter

  • Activating Interpreter:
python3
  • Test out Python commands quickly and easily.