Overview
This lecture covers Python fundamentals, including installation, syntax basics, variables, data types, strings, numbers, operators, loops, and functions, with practical examples and best practices for beginners.
Getting Started with Python
- Download Python from python.org and install the latest version (Python 3 recommended).
- Add Python to system PATH during installation for command-line access.
- Verify installation via terminal:
python --version (Windows), python3 --version (Mac/Linux).
- Use the Python interpreter (interactive shell) or write code in files.
Setting Up the Coding Environment
- Use a code editor (e.g., VS Code) or IDE for Python development.
- Install the official Python extension in VS Code for added features: linting, debugging, auto-completion, code formatting, testing, and snippets.
- Format code automatically using autopep8 and follow PEP 8 style guidelines.
Python Basics: Syntax & Data Types
- Expressions are code that produce values (e.g., 2 + 2).
- Syntax errors occur when code grammar is incorrect.
- Variables store data in memory; use descriptive, lowercase names with underscores.
- Primitive types: integers, floats, booleans (True/False), strings (text).
Working with Strings
- Strings can be enclosed in single, double, or triple quotes.
- Get length:
len(string).
- Indexing uses brackets (e.g.,
string[0]); negative indices start from the end.
- Slicing:
string[start:end] returns a substring.
- Escape sequences:
\n (new line), \\ (backslash), \" (double quote).
- String methods:
upper(), lower(), title(), strip(), find(), replace().
- Use
in and not in to check membership.
Numbers and Mathematical Operations
- Number types: int, float, complex (
a + bj).
- Operators: +, -, *, / (float division), // (integer division), % (modulus), ** (exponent).
- Functions:
round(), abs(), and math module functions (import with import math).***
User Input & Type Conversion
- Use
input() to get user input (always returns a string).
- Convert types with
int(), float(), bool(), and str().
- "Truthy" and "falsy" values: empty strings, 0, and None are falsy.
Comparison & Logical Operators
- Comparison: >, >=, <, <=, ==, != (can be used with numbers and strings).
- Logical:
and (both true), or (at least one true), not (inverse).
- Chain comparisons:
18 <= age < 65.
Conditional Statements
- Use
if, elif, and else for decision-making, using indentation to define code blocks.
- Ternary operator:
x = value_if_true if condition else value_if_false.
Loops
- For loop:
for item in iterable:; use with range(start, stop, step).
- Break statement exits a loop early;
else after loop runs if loop completes without break.
- Nested loops: loops inside loops for multiple dimensions (e.g., coordinates).
- While loop repeats as long as a condition is true; beware of infinite loops (exit with
break).
Functions
- Define with
def function_name(parameters): and indent function body.
- Use descriptive names and proper formatting (2 lines between functions).
- Parameters are inputs to functions; arguments are the supplied values.
- Return values with
return; if none, function returns None by default.
- Optional parameters have default values; they must come after required parameters.
- Use
*args to accept a variable number of arguments (packed as a tuple).
- Use keyword arguments to clarify intent.*
Key Terms & Definitions
- Expression — code that produces a value.
- Syntax error — an error due to incorrect code grammar.
- Linter — tool for checking code for errors and style issues.
- PEP 8 — Python Enhancement Proposal 8, style guide for code formatting.
- Boolean — data type with values
True or False.
- Iterable — object that can be looped over (e.g., list, string, range).
- Ternary operator — compact if-else assignment.
- Tuple — immutable sequence, created with parentheses.
- Optional parameter — function parameter with a default value.
Action Items / Next Steps
- Install Python and VS Code with the Python extension.
- Practice using print, variables, data types, and string methods.
- Complete exercises: even-number print, input handling, function definition.
- Read PEP 8 for code style guidance.
- Experiment with math module functions and different kinds of loops.