Introduction to Python
中文版:Python 入门
A hands-on introduction to Python programming: variables, data types, operators, control flow, functions, classes, and file I/O.
Overview
Python is a high-level, interpreted programming language widely used in data science and big data analytics. This lecture covers the foundational concepts needed to write Python programs, from basic syntax to object-oriented programming.
Info
Python uses dynamic typing — the data type of a variable is determined automatically at runtime, and variables can be reassigned to values of different types freely.
Development Environments
Common integrated development environments (IDEs) for Python:
| IDE | Description |
|---|---|
| PyCharm | A powerful, feature-rich IDE developed by JetBrains with a wide range of tools and features. |
| JupyterLab | A flexible web-based editor developed by the community, started as a next-generation interface for Jupyter notebooks. |
| VS Code | A lightweight yet powerful code editor developed by Microsoft, highly extensible. |
Variables and Dynamic Typing
A variable is a name that refers to a value stored in memory. Variables are created with an assignment statement (=):
x = 42
hours = 35.0
rate = 12.50
pay = hours * rate
print(pay)Because Python uses dynamic typing, you do not need to declare the type of a variable in advance. The type is inferred from the assigned value and can change during execution:
x = 42 # x is an integer
x = "First year" # Now x is a stringHowever, incompatible operations are caught at runtime:
x = 5
y = "text"
print(x + y) # Error: unsupported operand type(s) for +: 'int' and 'str'Variable Naming Rules
- Must start with a letter or underscore
_ - Case sensitive (
spam,Spam, andSPAMare different variables) - Cannot use reserved words as identifiers
Valid names: spam, eggs, spam23, _speed
Invalid names: 23spam, #sign, var.12
Reserved Words
False class return is finally
None if for lambda continue
True def from while nonlocal
and del global not with
as elif try or yield
assert else import pass
break except in raise
Data Types
Python provides several built-in data types, summarized below:
| Data Type | Category | Description | Mutability |
|---|---|---|---|
int | Numeric | Integer number (e.g., 5, -3). | Immutable |
float | Numeric | Floating-point numbers (e.g., 3.14, -0.5). | Immutable |
complex | Numeric | Complex numbers (e.g., 3+4j). | Immutable |
str | Text | Sequence of Unicode characters (e.g., "hello"). | Immutable |
bool | Boolean | Boolean values: True or False. | Immutable |
list | Sequence | Ordered, mutable collection (e.g., [1, "a", True]). | Mutable |
tuple | Sequence | Ordered, immutable collection (e.g., (1, "a", True)). | Immutable |
range | Sequence | Immutable sequence of numbers (e.g., range(5)). | Immutable |
dict | Mapping | Unordered key-value pairs (e.g., {"name": "Alice"}). | Mutable |
set | Set | Unordered collection of unique elements (e.g., {1, 2, 3}). | Mutable |
NoneType | None | Represents the absence of a value (None). | Immutable |
Numeric Types
# Integer
age = 25
print(age) # Output: 25
# Float
price = 19.99
print(price) # Output: 19.99
# Complex
z = 3 + 4j
print(z.real) # Output: 3.0
print(z.imag) # Output: 4.0Boolean Type
is_empty = False
print(5 > 3) # Output: True
print(5 < 3) # Output: False
print(not is_empty) # Output: TrueText Type
greeting = "Hello, Python!"
print(greeting[0:5]) # Output: Hello
print(len(greeting)) # Output: 13Sequence Types
# List (mutable)
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
# Tuple (immutable)
colors = ("red", "green", "blue")
print(colors[1]) # Output: green
# colors[1] = "yellow" # Error: tuples are immutable
# Range
numbers = list(range(1, 10, 2))
print(numbers) # Output: [1, 3, 5, 7, 9]
numbers = range(5) # 0, 1, 2, 3, 4; start = 0; step = 1
print(list(numbers)) # Output: [0, 1, 2, 3, 4]Mapping Type
# Dictionary (dict)
person = {
"name": "Alice",
"age": 30,
"city": "Paris"
}
print(person["name"]) # Output: Alice
person["email"] = "alice@example.com" # Add new key-value pairSet Type
# Set (mutable, unique elements)
unique_numbers = {1, 2, 2, 3}
print(unique_numbers) # Output: {1, 2, 3} (duplicates removed)
unique_numbers.add(40)
print(unique_numbers) # Output: {1, 2, 3, 40}Warning
Sets are unordered collections. Accessing elements by index (e.g.,
my_set[0]) raises aTypeError.
NoneType
result = None
print(result) # Output: NoneType Checking and Conversion
a = 2
print(type(a)) # <class 'int'>
a = float(a) # 2.0
a = str(a) # '2'Operators
Arithmetic Operators
| Operator | Operation |
|---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
** | Power |
% | Remainder (modulus) |
// | Floor division |
a = 10
b = 3
print("Sum:", a + b) # 13
print("Difference:", a - b) # 7
print("Product:", a * b) # 30
print("Quotient:", a / b) # 3.333...
print("Modulus:", a % b) # 1
print("Exponent:", a ** b) # 1000
print("Floor division:", a // b) # 3Math Module
import math
print(math.sqrt(25)) # 5.0
print(math.sqrt(4)) # 2.0
print(math.pow(4, 2)) # 16.0
x = [1.12, 2, 3]
print(math.fsum(x)) # 6.12 (high precision for floats)
print(sum(x)) # 6.12 (built-in function)Comparison Operators
Used for conditions and if statements:
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal |
<= | Less than or equal |
Logical Operators
Used for combining conditions:
| Operator | Meaning |
|---|---|
and | True if both operands are true |
or | True if at least one operand is true |
not | Reverses the boolean value |
Control Flow
If Statements
Blocks in Python are defined by indentation (4 spaces or a tab). Colons : are used to start blocks.
num = float(input("Enter a number: "))
if num > 0:
print("Positive!")
elif num < 0:
print("Negative!")
else:
print("Zero!")Combining Conditions
num = 15
if 10 <= num <= 20:
print("In range!")
else:
print("Out of range!")
username = input("Username: ")
password = input("Password: ")
if username == "admin" and password == "1234":
print("Login successful!")
else:
print("Invalid credentials.")For Loops
# Print numbers from 1 to 5
for i in range(1, 6):
print(i)
# Sum all numbers in a list
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print("Sum:", total) # 15While Loops
# Countdown from 5 to 1
count = 5
while count > 0:
print(count)
count -= 1Continue and Break
# Skip even numbers using continue
for i in range(10):
if i % 2 == 0:
continue
print(i) # Prints 1, 3, 5, 7, 9
# Stop loop when a condition is met using break
for num in range(1, 100):
if num % 7 == 0:
print("First multiple of 7:", num) # 7
breakNested Loops
# Multiplication table (1 to 3)
for i in range(1, 2):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}")
print("------")Collections: Lists and Sets
List Operations and Slicing
# List comprehension
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
# Slicing
my_list = [0, 1, 2, 3, 4]
print(my_list[1:4]) # [1, 2, 3] (index 1 to 3)
print(my_list[::-1]) # [4, 3, 2, 1, 0] (reverse)Set Operations
my_set = {1, 'Hello', 2, 2} # {1, 'Hello', 2} (unique elements)
# Convert to list for indexed access
my_list = list(my_set)
print(my_list[0]) # Output varies (order not guaranteed)
# Iterate over a set
for item in my_set:
print(item)
# Check for membership
if 'Hello' in my_set:
print("Found 'Hello'!")
# Remove and return an arbitrary element
element = my_set.pop()
print(element)Functions and Classes
Functions
A user-defined function is a block of organized, reusable code that helps break down larger programs into manageable units.
# Function to add two numbers
def add(x, y):
return x + y
result = add(5, 3)
print("5 + 3 =", result) # 8
# Function with default parameter
def greet(name="Guest"):
print("Hello,", name)
greet("Alice") # Hello, Alice
greet() # Hello, GuestClasses
Classes are a fundamental building block of object-oriented programming (OOP) in Python.
class Dog:
def __init__(self, name, age):
self.name = name # Constructor initializes instance attributes
self.age = age
def bark(self):
print(f"{self.name} says woof!")
# Create an object/instance
my_dog = Dog('XiaoHuang', 2)
print('my dog name is', my_dog.name) # my dog name is XiaoHuang
print('my dog age is', my_dog.age) # my dog age is 2
my_dog.bark() # Output: XiaoHuang says woof!File I/O
Writing and Reading Files
# Write to a file
with open("file.txt", "w") as f:
f.write("Hello, Python!")
# Read from a file
with open("file.txt", "r") as f:
content = f.read() # "Hello, Python!"
print(type(content), content)User Input
nam = input('what is your name?')
print('Welcome', nam) # Welcome <your input>String Formatting
# f-strings (Python 3.6+)
name = "Alice"
print(f"Hello, {name}!") # Hello, Alice!
num = 2
print(f'Hello,{name}! num={num}#')
# .format() method
print("Value: {}".format(10)) # Value: 10
# Simple concatenation
print('value:', name, '!', 'key:', num) # value: Alice ! key: 2Comments
# Single-line comment
"""
Multi-line comment
using triple quotes (also used for docstrings).
"""Tip
In most IDEs, you can select lines of code and press
Ctrl + /to toggle comments quickly.
Mini Project: Number Guessing Game
A complete example combining variables, loops, conditionals, and user input:
import random
secret_number = random.randint(1, 5)
attempts = 3
while attempts > 0:
guess = int(input("Guess a number (1-5): "))
if guess == secret_number:
print("You won!")
break
else:
attempts -= 1
print(f"Wrong! {attempts} attempts left.")
else:
print(f"Game over! The number was {secret_number}.")Summary
| Topic | Key Points |
|---|---|
| Variables | Dynamic typing, assignment with =, naming rules |
| Data Types | Numeric, text, boolean, sequence, mapping, set, NoneType |
| Operators | Arithmetic, comparison, logical; math module |
| Control Flow | if/elif/else, for, while, continue, break |
| Collections | Lists (mutable, ordered), sets (unique, unordered), tuples (immutable) |
| Functions | def, parameters, default values, return |
| Classes | class, __init__, methods, instances |
| File I/O | open(), with statement, read(), write() |
Related Concepts
- Python Variables — Variable assignment and dynamic typing
- Python Data Types — Built-in types and mutability
- Python Control Flow — Conditionals and loops
- Python Functions and Classes — Reusable code and OOP
- O — Reading and writing files