Fundamentals 24 min read

Comprehensive Python 3 Basics: Syntax, Data Types, Control Flow, Functions, Modules, and More

This article provides a thorough introduction to Python 3, covering fundamental syntax, core data types, operators, control structures, functions, modules, file I/O, error handling, object‑oriented concepts, and common standard‑library utilities, complete with runnable code examples for each topic.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Comprehensive Python 3 Basics: Syntax, Data Types, Control Flow, Functions, Modules, and More

1. Python3 Basic Syntax

Python uses indentation (typically four spaces) to define code blocks, each line represents a statement, and variables are created by simple assignment without explicit type declaration.

2. Python3 Basic Data Types

Python includes integers, floats, strings, and booleans. Example code:

# 创建整数
a = 10
b = -5
# 基本运算
sum_ab = a + b  # 加法
diff_ab = a - b  # 减法
product_ab = a * b  # 乘法
quotient_ab = a // b  # 整除
remainder_ab = a % b  # 取模(余数)
power_ab = a ** b  # 幂
print(sum_ab)       # 输出: 5
print(diff_ab)      # 输出: 15
print(product_ab)   # 输出: -50
print(quotient_ab)  # 输出: -2
print(remainder_ab) # 输出: 0
print(power_ab)     # 输出: 0.0001
print(type(a))      # 输出: <class 'int'>
# 创建浮点数
x = 3.14
y = -2.718
# 基本运算
sum_xy = x + y  # 加法
diff_xy = x - y  # 减法
product_xy = x * y  # 乘法
quotient_xy = x / y  # 除法
power_xy = x ** y  # 幂
print(sum_xy)       # 输出: 0.422
print(diff_xy)      # 输出: 5.858
print(product_xy)   # 输出: -8.53952
print(quotient_xy)  # 输出: -1.155506858130294
print(power_xy)     # 输出: 0.04305006074309672
print(type(x))      # 输出: <class 'float'>
# 创建字符串
greeting = "Hello, World!"
name = 'Alice'
# 字符串拼接
full_greeting = greeting + " My name is " + name
print(full_greeting)  # 输出: Hello, World! My name is Alice
# 字符串格式化
age = 25
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)  # 输出: My name is Alice and I am 25 years old.
# 使用 .format()
formatted_string_2 = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string_2)  # 输出: My name is Alice and I am 25 years old.
# 访问字符
print(greeting[0])  # 输出: H
# 切片
print(greeting[7:])  # 输出: World!
print(greeting[:5])  # 输出: Hello
print(greeting[3:9]) # 输出: lo, Wo
# 字符串长度
print(len(greeting))  # 输出: 13
# 字符串方法
upper_greeting = greeting.upper()  # 转换为大写
lower_greeting = greeting.lower()  # 转换为小写
title_greeting = greeting.title()  # 每个单词首字母大写
print(upper_greeting)  # 输出: HELLO, WORLD!
print(lower_greeting)  # 输出: hello, world!
print(title_greeting)  # 输出: Hello, World!
# 替换子字符串
replaced_greeting = greeting.replace("World", "Python")
print(replaced_greeting)  # 输出: Hello, Python!
print(type(greeting))  # 输出: <class 'str'>
# 创建布尔值
is_true = True
is_false = False
# 布尔运算
and_result = is_true and is_false  # 逻辑与
or_result = is_true or is_false    # 逻辑或
not_result = not is_true           # 逻辑非
print(and_result)  # 输出: False
print(or_result)   # 输出: True
print(not_result)  # 输出: False
# 与其他类型的转换
zero = 0
non_zero = 10
empty_list = []
non_empty_list = [1, 2, 3]
print(bool(zero))         # 输出: False
print(bool(non_zero))     # 输出: True
print(bool(empty_list))   # 输出: False
print(bool(non_empty_list))  # 输出: True
print(type(is_true))  # 输出: <class 'bool'>

类型转换

Python provides built‑in functions to convert between types, such as int() , float() , str() , and bool() .

num_str = "100"
num_int = int(num_str)  # 转换为整数
num_float = float(num_str)  # 转换为浮点数
print(num_int)  # 输出: 100
print(num_float)  # 输出: 100.0
zero = 0
non_zero = 1
empty_list = []
non_empty_list = [1, 2, 3]
print(bool(zero))         # 输出: False
print(bool(non_zero))     # 输出: True
print(bool(empty_list))   # 输出: False
print(bool(non_empty_list))  # 输出: True
number = 123
string_number = str(number)
print(string_number)  # 输出: 123

3. Python3 Interpreter

The Python interpreter runs code via the command line or interactive mode.

python -c "print('Hello, World!')"
>> print("Hello, World!")
Hello, World!

4. Python3 Comments

Single‑line comments start with # ; multi‑line comments use triple quotes.

# This is a single‑line comment
print("Hello, World!")
"""
This is a multi‑line comment
It can span multiple lines
"""
print("This is an example of a multi‑line comment")

5. Python3 Operators

Arithmetic, comparison, logical, and bitwise operators are demonstrated below.

a = 10
b = 3
# Arithmetic operators
print(a + b)  # 加法
print(a - b)  # 减法
print(a * b)  # 乘法
print(a / b)  # 除法
print(a % b)  # 取模
print(a // b)  # 整除
print(a ** b)  # 幂
# Comparison operators
print(a == b)  # 等于
print(a != b)  # 不等于
print(a > b)   # 大于
print(a < b)   # 小于
print(a >= b)  # 大于等于
print(a <= b)  # 小于等于
# Logical operators
print(a > 0 and b > 0)  # 与
print(a > 0 or b > 0)   # 或
print(not (a > 0))      # 非

6. Python3 Numbers

a = 10          # int
b = 3.14        # float
c = 2 + 3j      # complex
print(type(a))  # 输出: <class 'int'>
print(type(b))  # 输出: <class 'float'>
print(type(c))  # 输出: <class 'complex'>

7. Python3 Strings

s = "Hello, World!"
print(s[0])          # 输出: H
print(s[0:5])        # 输出: Hello
print(len(s))        # 输出: 13
print(s.upper())     # 输出: HELLO, WORLD!
print(s.lower())     # 输出: hello, world!
print(s.title())     # 输出: Hello, World!
print(s.replace("World", "Python"))  # 输出: Hello, Python!

8. Python3 Lists

fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # 输出: apple
fruits[0] = "orange"
print(fruits)  # 输出: ['orange', 'banana', 'cherry']
fruits.append("grape")
print(fruits)  # 输出: ['orange', 'banana', 'cherry', 'grape']
fruits.insert(1, "kiwi")
print(fruits)  # 输出: ['orange', 'kiwi', 'banana', 'cherry', 'grape']
fruits.remove("banana")
print(fruits)  # 输出: ['orange', 'kiwi', 'cherry', 'grape']
fruits.sort()
print(fruits)  # 输出: ['cherry', 'grape', 'kiwi', 'orange']

9. Python3 Tuples

coordinates = (10, 20)
print(coordinates[0])  # 输出: 10
x, y = coordinates
print(x, y)  # 输出: 10 20

10. Python3 Dictionaries

person = {"name": "Alice", "age": 25, "city": "New York"}
print(person["name"])  # 输出: Alice
person["age"] = 26
print(person)  # 输出: {'name': 'Alice', 'age': 26, 'city': 'New York'}
person["email"] = "[email protected]"
print(person)  # 输出: {'name': 'Alice', 'age': 26, 'city': 'New York', 'email': '[email protected]'}
del person["city"]
print(person)  # 输出: {'name': 'Alice', 'age': 26, 'email': '[email protected]'}
print(person.keys())   # 输出: dict_keys(['name', 'age', 'email'])
print(person.values()) # 输出: dict_values(['Alice', 26, '[email protected]'])
print(person.items())  # 输出: dict_items([('name', 'Alice'), ('age', 26), ('email', '[email protected]')])

11. Python3 Sets

fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
print(fruits)  # 输出: {'banana', 'cherry', 'apple', 'orange'}
fruits.remove("banana")
print(fruits)  # 输出: {'cherry', 'apple', 'orange'}
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2))      # 输出: {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # 输出: {3}
print(set1.difference(set2))   # 输出: {1, 2}

12. Python3 Conditional Control

age = 20
if age < 18:
    print("未成年")
elif age >= 18 and age < 60:
    print("成年")
else:
    print("老年")

13. Python3 Loops

# for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
# while loop
count = 0
while count < 5:
    print(count)
    count += 1

14. Python3 First Program

print("Hello, World!")

15. Python3 Comprehensions

# List comprehension
squares = [x ** 2 for x in range(10)]
print(squares)  # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Dictionary comprehension
squares_dict = {x: x ** 2 for x in range(10)}
print(squares_dict)  # 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
# Set comprehension
squares_set = {x ** 2 for x in range(10)}
print(squares_set)  # 输出: {0, 1, 64, 4, 36, 9, 16, 81, 49, 25}

16. Python3 Iterators and Generators

# Iterator
my_list = [1, 2, 3]
my_iter = iter(my_list)
print(next(my_iter))  # 输出: 1
print(next(my_iter))  # 输出: 2
print(next(my_iter))  # 输出: 3
# Generator
def generate_numbers(n):
    for i in range(n):
        yield i
gen = generate_numbers(5)
for num in gen:
    print(num)  # 输出: 0 1 2 3 4

17. Python3 Functions

def greet(name):
    return f"你好, {name}!"
print(greet("Alice"))  # 输出: 你好, Alice!

18. Python3 Lambda

add = lambda x, y: x + y
print(add(3, 5))  # 输出: 8

19. Python3 Decorators

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper
@my_decorator
def say_hello():
    print("Hello!")
say_hello()

20. Python3 Data Structures Overview

Python provides built‑in containers: lists (ordered, mutable), tuples (ordered, immutable), dictionaries (unordered key‑value pairs), and sets (unordered, unique elements). Representative examples are shown in the earlier sections.

21. Python3 Modules

# Import entire module
import math
print(math.sqrt(16))  # 输出: 4.0
# Import specific name
from datetime import datetime
now = datetime.now()
print(now)  # 输出: 当前日期和时间

22. Python3 Input and Output

name = input("请输入你的名字: ")
print(f"你好, {name}!")

23. Python3 File Operations

# Write to a file
with open("example.txt", "w") as file:
    file.write("Hello, World!\n")
# Read from a file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)  # 输出: Hello, World!

24. Python3 OS Module

import os
current_dir = os.getcwd()
print(current_dir)
files = os.listdir(".")
print(files)
os.mkdir("new_folder")
os.rmdir("new_folder")

25. Python3 Errors and Exceptions

try:
    result = 10 / 0
except ZeroDivisionError:
    print("除零错误")
finally:
    print("无论是否发生异常,都会执行这里")
# Manually raise an exception
raise ValueError("这是一个自定义的错误")

26. Python3 Object‑Oriented Programming

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")
person = Person("Alice", 25)
print(person.name)  # 输出: Alice
person.greet()  # 输出: Hello, my name is Alice and I am 25 years old.

27. Python3 Namespace and Scope

x = 10  # 全局变量
def outer_function():
    y = 20  # 局部变量
    def inner_function():
        z = 30  # 局部变量
        print(z)  # 输出: 30
        print(y)  # 输出: 20
        print(x)  # 输出: 10
    inner_function()
outer_function()

28. Python3 Standard Library Overview

import os, sys, math, datetime, random, re, json
print(os.getcwd())
print(sys.version)
print(math.pi)
print(datetime.datetime.now())
print(random.randint(1, 10))
print(re.match(r'\d+', '123abc'))
print(json.dumps({"name": "Alice", "age": 25}))
PythonprogrammingData TypestutorialFunctionsbasics
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.