Fundamentals 33 min read

Python Basics: Print, Variables, Data Types, Control Flow, Functions, and More

This comprehensive tutorial introduces Python fundamentals, covering print statements, variable definition and assignment, data type conversion, conditional and loop structures, function creation and invocation, input handling, comments, indentation rules, program exit methods, operators, slicing, collections, file I/O, exception handling, and module imports.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Basics: Print, Variables, Data Types, Control Flow, Functions, and More

Print Output (print())

Demonstrates printing strings, variable values, formatted f-strings, multiple variables with spaces, and controlling line endings.

# 输出简单的欢迎信息
print("欢迎来到Python编程世界!")

name = "Alice"
# 输出变量的值,使用逗号分隔不同的参数
print("你好,", name)

age = 25
# 使用f-string嵌入变量到字符串中
print(f"我今年{age}岁了。")

first_name = "张"
last_name = "三"
# 输出多个变量,自动以空格分隔
print(first_name, last_name)

# 使用end参数控制输出后不换行,默认是换行符'\n'
print("这是第一行", end=" ")
print("这是在同一行继续输出的内容")

Variable Definition and Assignment

Shows how to define and assign integers, floats, multiple variables at once, reassign values, and perform calculations.

# 定义一个整数类型的变量
my_age = 28
print(my_age)  # 输出变量的值

# 定义一个浮点数类型的变量
pi_value = 3.14159
print(pi_value)  # 输出变量的值

# 同时给多个变量赋值
x, y, z = 1, 2, 3
print(x, y, z)  # 输出所有变量的值

# 变量可以被重新赋值
counter = 0
counter = counter + 1
print(counter)  # 输出更新后的值

# 变量可以参与数学运算
price = 9.99
quantity = 3
total_cost = price * quantity
print(total_cost)  # 输出总成本

Data Type Conversion

Illustrates converting strings to integers, floats to strings, lists to tuples, tuples to sets, and creating dictionaries.

# 将字符串形式的数字转换为整数
num_str = "100"
num_int = int(num_str)
print(num_int)  # 输出转换后的整数

# 将浮点数转换为字符串
num_float = 3.14
num_str = str(num_float)
print(num_str)  # 输出转换后的字符串

# 将列表转换为元组
list_items = [1, 2, 3]
tuple_items = tuple(list_items)
print(tuple_items)  # 输出转换后的元组

# 将元组转换为集合,去除重复元素
tuple_data = (1, 2, 2, 3, 4, 4)
set_data = set(tuple_data)
print(set_data)  # 输出转换后的集合

# 使用键值对创建字典
dict_data = dict(name="李四", age=30)
print(dict_data)  # 输出字典

Conditional Statements

Provides examples of simple if, if‑else, if‑elif‑else, nested conditions, and compound logical checks.

score = 60
if score >= 60:
    print("及格")  # 如果分数大于等于60,输出及格

temperature = 75
if temperature > 80:
    print("天气炎热")
else:
    print("天气凉爽")

user_input = 3
if user_input == 1:
    print("选择了选项一")
elif user_input == 2:
    print("选择了选项二")
else:
    print("选择了其他选项")

is_student = True
grade = 90
if is_student:
    if grade >= 90:
        print("优秀学生")
    else:
        print("普通学生")
else:
    print("非学生")

height = 175
weight = 70
if height > 170 and weight < 80:
    print("符合标准")

Loop Statements

Shows for loops over lists, range usage, while loops, list comprehensions, and break statements.

fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
    print(fruit)  # 遍历列表中的每个元素,并打印出来

for i in range(1, 5):  # 从1开始到4结束(不包括5)
    print(i)  # 打印当前索引

count = 0
while count < 5:
    print(count)  # 当count小于5时,打印count的值
    count += 1  # 每次循环后增加count的值

squares = [x**2 for x in range(10)]
for square in squares:
    print(square)  # 使用列表解析生成平方数列表,并遍历打印

for number in range(1, 10):
    if number == 5:
        break  # 当number等于5时,跳出循环
    print(number)

Function Definition

Defines simple functions, functions with parameters, return values, default arguments, and variable‑length arguments.

def greet():
    """这是一个简单的问候函数"""
    print("你好,欢迎来到Python的世界!")  # 打印欢迎信息
greet()  # 调用greet函数

def say_hello(name):
    """根据传入的名字打印个性化问候"""
    print(f"你好, {name}!")  # 使用f-string格式化字符串
say_hello("小明")  # 调用say_hello函数并传递参数

def add_numbers(a, b):
    """返回两个数相加的结果"""
    return a + b  # 返回计算结果
result = add_numbers(5, 3)  # 调用add_numbers函数并接收返回值
print(result)  # 输出结果

def describe_pet(pet_name, animal_type='狗'):
    """描述宠物的信息"""
    print(f"\n我有一只{animal_type}。")
    print(f"我的{animal_type}叫{pet_name}。")
describe_pet('旺财')  # 使用默认参数调用describe_pet函数
describe_pet('汤姆', '猫')  # 传递所有参数调用describe_pet函数

def make_pizza(*toppings):
    """打印顾客点的所有配料"""
    print("\n制作披萨需要以下配料:")
    for topping in toppings:
        print(f"- {topping}")
make_pizza('蘑菇', '青椒', '培根')  # 调用make_pizza函数并传递多个参数

Function Calls

Examples of calling functions without parameters, with arguments, with return values, keyword arguments, and variable‑length arguments.

def welcome_message():
    """显示欢迎消息"""
    print("欢迎使用我们的服务!")
welcome_message()  # 直接调用函数

def display_message(message):
    """显示传递的消息"""
    print(message)
display_message("这是通过函数传递的消息。")  # 调用函数并传递参数

def get_formatted_name(first_name, last_name):
    """返回整洁的姓名"""
    full_name = f"{first_name} {last_name}"
    return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')  # 调用函数获取返回值
print(musician)  # 打印返回值

def build_profile(first, last, **user_info):
    """创建一个字典,其中包含我们知道的有关用户的一切"""
    user_info['first_name'] = first
    user_info['last_name'] = last
    return user_info
user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)  # 调用函数并传递关键字参数

def make_sandwich(*items):
    """列出三明治中的所有配料"""
    print("\n正在为您制作含有以下配料的三明治:")
    for item in items:
        print(f"- {item}")
make_sandwich('火腿', '奶酪', '生菜')  # 调用函数并传递多个参数

Input Functions

Shows how to read user input, convert it, store multiple inputs, process numeric input, and combine with conditional logic.

name = input("请输入您的名字: ")  # 提示用户输入
print(f"您好, {name}!")  # 输出用户输入的名字

age = int(input("请输入您的年龄: "))  # 将输入转换为整数
next_year_age = age + 1
print(f"明年您将会是 {next_year_age} 岁。")

hobbies = []  # 创建空列表来保存爱好
hobby = input("请输入您的爱好 (输入'结束'来停止): ")
while hobby != '结束':
    hobbies.append(hobby)  # 添加到列表
    hobby = input("请输入您的下一个爱好 (输入'结束'来停止): ")
print("您的爱好有:", hobbies)

height = float(input("请输入您的身高(米): "))
weight = float(input("请输入您的体重(千克): "))
bmi = weight / (height * height)  # 计算BMI指数
print(f"您的BMI指数是 {bmi:.2f}")  # 格式化输出保留两位小数

answer = input("您喜欢编程吗?(yes/no): ")
if answer.lower() == 'yes':
    print("太棒了,继续加油!")
else:
    print("没关系,每个人都有自己的兴趣。")

Comments

Demonstrates single‑line comments, multi‑line comments, docstrings, and commenting out code.

# 这是一个单行注释
print("Hello, World!")  # 在打印语句后添加注释

''' 
这是一段多行注释,
用来解释下面这段代码的功能。
''' 
print("这是一段测试代码。")

def square_number(n):
    """
    返回给定数字的平方。
    参数 n: 要求平方的数字
    返回: 数字的平方
    """
    return n * n
print(square_number(4))  # 调用square_number函数

# print("这条消息不会被打印出来。")
print("这条消息会被打印出来。")

# 计算阶乘
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)  # 递归调用自身
print(factorial(5))  # 输出5的阶乘

Indentation

Shows correct and incorrect indentation for if statements, loops, functions, and nested structures.

age = 20
if age >= 18:
    print("成年人")  # 正确缩进,属于if块
print("检查完成")  # 不属于if块

for i in range(5):
    print(i)  # 每次循环都会执行,并且正确缩进
print("循环结束")  # 循环结束后执行,不缩进

def my_function():
    print("这是函数内部的代码")  # 函数体内的代码必须缩进
my_function()  # 调用函数

def another_function():
print("如果没有正确缩进,会抛出IndentationError")  # 这里缺少缩进,会导致错误

if True:
    print("外层条件成立")
    if False:
        print("内层条件不成立")  # 内层条件的代码块
    else:
        print("内层条件成立")  # 内层else部分的代码块

Program Exit

Illustrates using exit() and sys.exit() with status codes, both in scripts and inside functions.

print("程序开始")
exit()  # 程序在此处停止,不会执行后续代码
print("这行代码不会被执行")  # 此行代码不会被执行

import sys
print("尝试正常退出...")
sys.exit(0)  # 以状态码0退出,表示正常结束

import sys
def divide(a, b):
    if b == 0:
        print("除数不能为零")
        sys.exit(1)  # 错误退出,状态码为1
    return a / b
result = divide(10, 0)

import sys
try:
    raise ValueError("触发一个值错误")
except ValueError:
    print("捕获到异常,准备退出程序")
    sys.exit(2)  # 根据异常类型选择不同的退出状态码

user_input = input("请输入'y'来继续:")
if user_input != 'y':
    print("用户决定退出")
    exit()  # 用户决定不继续,则退出程序
print("继续执行程序...")  # 只有当用户输入'y'时才会执行

Arithmetic Operators

Shows addition, subtraction, multiplication, division, floor division, and modulo.

a = 5
b = 3
print(f"{a} + {b} = {a + b}")  # 输出: 5 + 3 = 8

a = 10
b = 4
print(f"{a} - {b} = {a - b}")  # 输出: 10 - 4 = 6

a = 7
b = 6
print(f"{a} * {b} = {a * b}")  # 输出: 7 * 6 = 42

a = 9
b = 2
print(f"{a} / {b} = {a / b}")  # 输出: 9 / 2 = 4.5

a = 11
b = 3
print(f"{a} // {b} = {a // b}, {a} % {b} = {a % b}")  # 输出: 11 // 3 = 3, 11 % 3 = 2

Logical Operators

Demonstrates and, or, not, combined logical expressions, and usage inside loops.

age = 20
has_license = True
if age >= 18 and has_license:
    print("可以合法驾驶")  # 当年龄大于等于18且有驾照时输出此消息

is_student = False
has_discount_card = True
if is_student or has_discount_card:
    print("可以享受折扣")  # 学生或有折扣卡都可以享受折扣

raining = False
if not raining:
    print("天气不错,适合外出")  # 如果不下雨,则适合外出

temperature = 22
humidity = 70
if temperature > 20 and humidity < 80:
    print("气候宜人")  # 温度高于20且湿度低于80时气候宜人

for i in range(1, 11):
    if i % 2 == 0 and i % 3 == 0:
        print(f"{i} 同时能被2和3整除")  # 打印同时能被2和3整除的数字

Identity Operators

Shows usage of is, is not, and id() to compare object identities.

x = ["apple", "banana"]
y = x
print(x is y)  # 输出: True,因为x和y引用同一个列表对象

x = ["apple", "banana"]
z = ["apple", "banana"]
print(x is not z)  # 输出: True,尽管内容相同,但它们是两个不同的对象

x = [1, 2, 3]
y = x
print(id(x), id(y))  # 输出相同的内存地址
print(x is y)  # 输出: True

a = None
b = None
if a is b:
    print("a和b都是None,或者引用同一对象")  # 输出: a和b都是None,或者引用同一对象

x = [1, 2, 3]
y = list(x)  # 创建一个新的列表,与x内容相同
print(x == y)  # 输出: True,因为它们的内容相等
print(x is y)  # 输出: False,因为它们不是同一个对象

Membership Operators

Demonstrates in and not in with lists, strings, and dictionaries.

fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
    print("香蕉在水果列表中")  # 输出: 香蕉在水果列表中

if "orange" not in fruits:
    print("橙子不在水果列表中")  # 输出: 橙子不在水果列表中

for fruit in ["apple", "banana", "cherry"]:
    if fruit in ["banana", "cherry"]:
        print(f"{fruit} 是我喜欢吃的水果之一")  # 输出喜欢的水果

sentence = "Hello, world!"
if "world" in sentence:
    print("找到了单词 'world'")  # 输出: 找到了单词 'world'

student_scores = {"Alice": 90, "Bob": 85}
if "Alice" in student_scores:
    print(f"Alice的成绩是 {student_scores['Alice']}")  # 输出: Alice的成绩是 90

Length Operations (len())

Shows using len() on strings, lists, tuples, dictionaries, and sets.

text = "Hello, World!"
print(f"字符串 '{text}' 的长度是 {len(text)}")  # 输出: 字符串 'Hello, World!' 的长度是 13

numbers = [1, 2, 3, 4, 5]
print(f"列表 {numbers} 中有 {len(numbers)} 个元素")  # 输出: 列表 [1, 2, 3, 4, 5] 中有 5 个元素

fruits = ("apple", "banana", "cherry")
print(f"元组 {fruits} 的大小是 {len(fruits)}")  # 输出: 元组 ('apple', 'banana', 'cherry') 的大小是 3

person = {"name": "Alice", "age": 25, "city": "New York"}
print(f"字典中有 {len(person)} 对键值对")  # 输出: 字典中有 3 对键值对

unique_numbers = {1, 2, 2, 3, 4, 4, 5}
print(f"集合 {unique_numbers} 包含 {len(unique_numbers)} 个唯一元素")  # 输出: 集合 {1, 2, 3, 4, 5} 包含 5 个唯一元素

Range Generator (range())

Illustrates basic range usage, even numbers, reverse ranges, list creation, and iterating with len().

for i in range(5):
    print(i)  # 输出: 0 1 2 3 4

for i in range(2, 11, 2):
    print(i)  # 输出: 2 4 6 8 10

for i in range(9, -1, -1):
    print(i)  # 输出: 9 8 7 6 5 4 3 2 1 0

numbers_list = list(range(1, 6))
print(f"创建的列表是 {numbers_list}")  # 输出: 创建的列表是 [1, 2, 3, 4, 5]

items = ["apple", "banana", "cherry"]
for i in range(len(items)):
    print(f"第{i+1}项是{items[i]}")  # 输出: 第1项是apple 第2项是banana 第3项是cherry

Slice Operations

Shows list slicing, negative indices, step slicing, full reversal, and slice assignment.

my_list = [0, 1, 2, 3, 4, 5]
slice_of_list = my_list[1:4]
print(f"切片后的列表是 {slice_of_list}")  # 输出: 切片后的列表是 [1, 2, 3]

my_string = "Python"
reversed_slice = my_string[-3:]
print(f"切片结果是 {reversed_slice}")  # 输出: 切片结果是 hon

my_tuple = (0, 1, 2, 3, 4, 5)
even_elements = my_tuple[::2]
print(f"每隔一个元素提取的结果是 {even_elements}")  # 输出: 每隔一个元素提取的结果是 (0, 2, 4)

sequence = "abcdef"
reversed_sequence = sequence[::-1]
print(f"反转后的序列是 {reversed_sequence}")  # 输出: 反转后的序列是 fedcba

letters = ['a', 'b', 'c', 'd', 'e']
letters[1:4] = ['B', 'C', 'D']
print(f"更新后的列表是 {letters}")  # 输出: 更新后的列表是 ['a', 'B', 'C', 'D', 'e']

List Comprehensions

Creates lists using comprehensions with expressions, filters, and transformations.

squares = [x**2 for x in range(1, 6)]
print(f"平方数列表是 {squares}")  # 输出: 平方数列表是 [1, 4, 9, 16, 25]

even_numbers = [num for num in range(1, 11) if num % 2 == 0]
print(f"偶数列表是 {even_numbers}")  # 输出: 偶数列表是 [2, 4, 6, 8, 10]

words = ["hello", "world", "python"]
upper_words = [word.upper() for word in words]
print(f"大写单词列表是 {upper_words}")  # 输出: 大写单词列表是 ['HELLO', 'WORLD', 'PYTHON']

pairs = [(x, y) for x in [1, 2, 3] for y in ['a', 'b']]
print(f"笛卡尔积列表是 {pairs}")  # 输出: 笛卡尔积列表是 [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]

mixed_data = [0, "apple", 1, "banana", 2, None, 3, ""]
filtered_data = [item for item in mixed_data if isinstance(item, int) and item > 0]
print(f"过滤并转换后的数据是 {filtered_data}")  # 输出: 过滤并转换后的数据是 [1, 2, 3]

Tuple Definition

Shows simple tuple creation, single‑element tuple syntax, unpacking, immutability, and using tuples as dictionary keys.

simple_tuple = (1, 2, 3)
print(f"简单元组是 {simple_tuple}")  # 输出: 简单元组是 (1, 2, 3)

single_element_tuple = (42,)
print(f"单元素元组是 {single_element_tuple}")  # 输出: 单元素元组是 (42,)

coordinates = (10, 20)
x, y = coordinates
print(f"x坐标是 {x}, y坐标是 {y}")  # 输出: x坐标是 10, y坐标是 20

immutable_tuple = (1, 2, 3)
try:
    immutable_tuple[0] = 4  # 尝试修改元组中的元素会导致错误
except TypeError as e:
    print(f"错误信息: {e}")  # 输出: 错误信息: 'tuple' object does not support item assignment

student_scores = {(1, "Alice"): 90, (2, "Bob"): 85}
print(f"Alice的成绩是 {student_scores[(1, 'Alice')]}")  # 输出: Alice的成绩是 90

Dictionary Definition

Creates dictionaries using literals, dict(), empty dicts, fromkeys, and shows basic operations.

person = {"name": "Alice", "age": 25}
print(f"字典内容: {person}")  # 输出: 字典内容: {'name': 'Alice', 'age': 25}

book = dict(title="Python编程", author="张三")
print(f"书的信息: {book}")  # 输出: 书的信息: {'title': 'Python编程', 'author': '张三'}

shopping_list = {"fruits": ["apple", "banana"], "vegetables": ["carrot", "lettuce"]}
print(f"购物清单: {shopping_list}")

empty_dict = {}
empty_dict["country"] = "China"
print(f"国家信息: {empty_dict}")  # 输出: 国家信息: {'country': 'China'}

default_values = {}.fromkeys(['height', 'width'], 0)
print(f"默认尺寸: {default_values}")  # 输出: 默认尺寸: {'height': 0, 'width': 0}

Dictionary Operations

Demonstrates get(), pop(), update(), clear(), and key existence checks.

user_info = {"name": "李四", "email": "[email protected]"}
email = user_info.get("email", "无邮箱信息")
print(f"用户邮箱: {email}")  # 输出: 用户邮箱: [email protected]

scores = {"math": 90, "english": 85}
math_score = scores.pop("math")
print(f"数学成绩已移除: {math_score}")  # 输出: 数学成绩已移除: 90

first_half = {"Q1": 100, "Q2": 200}
second_half = {"Q3": 300, "Q4": 400}
first_half.update(second_half)
print(f"全年业绩: {first_half}")  # 输出: 全年业绩: {'Q1': 100, 'Q2': 200, 'Q3': 300, 'Q4': 400}

inventory = {"apples": 30, "bananas": 45}
inventory.clear()
print(f"库存清空后: {inventory}")  # 输出: 库存清空后: {}

settings = {"theme": "dark", "language": "en"}
has_theme = "theme" in settings
print(f"是否有主题设置: {has_theme}")  # 输出: 是否有主题设置: True

File Operations

Shows opening files for reading, writing, appending, line‑by‑line reading, and using multiple context managers.

with open('example.txt', 'r') as file:
    content = file.read()
    print(f"文件内容: {content}")

with open('output.txt', 'w') as file:
    file.write("这是一个测试文件。")
    print("写入完成")

with open('output.txt', 'a') as file:
    file.write("\n这是追加的内容。")
    print("追加完成")

with open('example.txt', 'r') as file:
    for line in file:
        print(line.strip())  # 去掉每行末尾的换行符

with open('source.txt', 'r') as src, open('destination.txt', 'w') as dest:
    content = src.read()
    dest.write(content)
    print("复制完成")

Exception Handling

Provides try‑except‑finally, handling specific exceptions, else clause, and exception handling inside functions.

try:
    with open('nonexistent_file.txt', 'r') as f:
        content = f.read()
except FileNotFoundError as e:
    print(f"错误: {e}")
finally:
    print("无论是否发生异常,都会执行此代码")

try:
    number = int("abc")
except ValueError as e:
    print(f"错误: {e}")

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"除零错误: {e}")
except Exception as e:
    print(f"其他错误: {e}")

try:
    number = int("123")
except ValueError:
    print("输入不是一个有效的整数")
else:
    print(f"成功转换为整数: {number}")

def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        print("除数不能为零")
        return None
result = divide(10, 0)
if result is not None:
    print(f"结果是: {result}")

Module Import

Shows importing whole modules, specific objects, aliasing, wildcard import (not recommended), and dynamic imports.

import math
print(f"圆周率: {math.pi}")  # 输出: 圆周率: 3.141592653589793

from datetime import datetime
current_time = datetime.now()
print(f"当前时间: {current_time}")  # 输出: 当前时间: 2025-02-06 14:16:00.123456

import numpy as np
array = np.array([1, 2, 3])
print(f"数组: {array}")  # 输出: 数组: [1 2 3]

from os.path import *
print(f"当前工作目录: {getcwd()}")  # 输出: 当前工作目录: /path/to/current/working/directory

import importlib
json_module = importlib.import_module('json')
data = json_module.dumps({"key": "value"})
print(f"JSON字符串: {data}")  # 输出: JSON字符串: {"key": "value"}
PythonData TypesFunctionsvariablesProgramming Basicscontrol flow
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.