AITC Wiki

Introduction to Python

Python 入门

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:

IDEDescription
PyCharmA powerful, feature-rich IDE developed by JetBrains with a wide range of tools and features.
JupyterLabA flexible web-based editor developed by the community, started as a next-generation interface for Jupyter notebooks.
VS CodeA 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 string

However, 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, and SPAM are 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 TypeCategoryDescriptionMutability
intNumericInteger number (e.g., 5, -3).Immutable
floatNumericFloating-point numbers (e.g., 3.14, -0.5).Immutable
complexNumericComplex numbers (e.g., 3+4j).Immutable
strTextSequence of Unicode characters (e.g., "hello").Immutable
boolBooleanBoolean values: True or False.Immutable
listSequenceOrdered, mutable collection (e.g., [1, "a", True]).Mutable
tupleSequenceOrdered, immutable collection (e.g., (1, "a", True)).Immutable
rangeSequenceImmutable sequence of numbers (e.g., range(5)).Immutable
dictMappingUnordered key-value pairs (e.g., {"name": "Alice"}).Mutable
setSetUnordered collection of unique elements (e.g., {1, 2, 3}).Mutable
NoneTypeNoneRepresents 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.0

Boolean Type

is_empty = False
print(5 > 3)       # Output: True
print(5 < 3)       # Output: False
print(not is_empty)  # Output: True

Text Type

greeting = "Hello, Python!"
print(greeting[0:5])  # Output: Hello
print(len(greeting))  # Output: 13

Sequence 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 pair

Set 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 a TypeError.

NoneType

result = None
print(result)  # Output: None

Type Checking and Conversion

a = 2
print(type(a))   # <class 'int'>
a = float(a)     # 2.0
a = str(a)       # '2'

Operators

Arithmetic Operators

OperatorOperation
+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)  # 3

Math 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:

OperatorMeaning
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal
<=Less than or equal

Logical Operators

Used for combining conditions:

OperatorMeaning
andTrue if both operands are true
orTrue if at least one operand is true
notReverses 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)  # 15

While Loops

# Countdown from 5 to 1
count = 5
while count > 0:
    print(count)
    count -= 1

Continue 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
        break

Nested 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, Guest

Classes

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: 2

Comments

# 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

TopicKey Points
VariablesDynamic typing, assignment with =, naming rules
Data TypesNumeric, text, boolean, sequence, mapping, set, NoneType
OperatorsArithmetic, comparison, logical; math module
Control Flowif/elif/else, for, while, continue, break
CollectionsLists (mutable, ordered), sets (unique, unordered), tuples (immutable)
Functionsdef, parameters, default values, return
Classesclass, __init__, methods, instances
File I/Oopen(), with statement, read(), write()

Sources