Python Programming Lecture Notes
Introduction
- Purpose: Teach Python programming from basics to advanced concepts.
- Benefits: Popular, beginner-friendly language; widely used in jobs, automation, and scripting.
Installation
- Python: Go to python.org to download Python 3.x (recommended) or Python 2.x (legacy, not supported in the future).
- Text Editor (IDE): Recommended IDE is PyCharm from JetBrains for writing Python code.
Getting Started
- First Program: Print "Hello, World!". Scripts to draw simple shapes using print statements and use variables.
- Hello World Example:
print("Hello, World!")
Core Concepts
Variables
- Definition: Containers for storing data values
- Types: Strings, numbers, Booleans (true/false values)
- Usage:
character_name = "Alice"
character_age = 50
is_adult = True
Strings
- Creating:
phrase = "Hello, World!"
- Common Functions: lower(), upper(), isupper(), index(), replace()
- Slicing: Accessing individual characters by index
phrase[0] # first character
phrase[1:4] # substring from index 1 to 3
Numbers
- Arithmetic: Basic operations (+, -, *, /, %)
- Functions: abs(), pow(), max(), min(), round(), sqrt() (require 'math' module)
Getting User Input
- Input: Use
input(prompt)
to get data from the user
name = input("Enter your name: ")
print("Hello, " + name)
Control Flow
If Statements
if condition:
action
elif other_condition:
another_action
else:
action_if_all_false
- Boolean Logic: and, or, not
Loops
- While Loops: Repeat block while condition is true
while condition:
action
- For Loops: Repeat block for each item in collection
for item in collection:
action
for number in range(1, 11):
print(number)
- Break: Exit the loop
- Continue: Skip remainder of loop and start next iteration
Functions
Definition and Call
def say_hi(name):
print("Hello, " + name)
say_hi("Alice")
Return Statement
- Purpose: Return data from a function
def add(a, b):
return a + b
result = add(3, 5) # result = 8
Advanced Concepts
- Function Parameters: Pass multiple pieces of information to functions
- Default Parameters: Set default values for parameters
Data Structures
Lists
- Definition: Ordered collection of items
- Creating:
friends = ["Alice", "Bob", "Charlie"]
- Accessing Items: Indexing
friends[0]
- Modification: Append, insert, remove, clear, pop, etc.
Tuples
- Definition: Immutable lists
- Creating:
coordinates = (4, 5)
- Usage: Store values that shouldn’t change
Dictionaries
- Definition: Key-value pairs
- Creating:
{ "Apples": "Red", "Bananas": "Yellow" }
- Accessing Values: By key
dict["Apples"]
Error Handling
try:
action
except ExceptionType as e:
handle_exception(e)
File Operations
Reading Files
- Open File for reading:
open('filename', 'r')
- Reading Methods: read(), readline(), readlines()
file = open('employees.txt', 'r')
print(file.read()) # Read entire file
Writing Files
- Modes: 'w' (write), 'a' (append), 'r' (read)
file = open('employees.txt', 'a')
file.write("Toby - Human Resources")
file.close()
Modules
Using Modules
- Importing:
import module_name
, from module_name import *
Packages
- External Libraries: Install using pip
pip install library_name
Classes and Objects
Basics
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
student1 = Student("Alice", 20)
Methods
- Adding Methods: Define functions inside class
class Student:
def greet(self):
print("Hello, " + self.name)
Inheritance
class GraduateStudent(Student):
def __init__(self, name, age, degree):
super().__init__(name, age)
self.degree = degree
Miscellaneous
The Python Interpreter
- Usage: Interactive shell for quick Python execution
python3 # Open Python interpreter
Comments
- Single Line:
# Comment
- Multi-line: Triple quotes
''' comment '''
These notes are designed to help you recall and review the key material from the Python programming course, aiding you in your study and development as a Python programmer. Happy coding! 🐍