Fundamentals 4 min read

Python Basics: Variables, Data Types, Control Structures, and Functions

This tutorial introduces Python fundamentals, covering variables and data types, control structures like if, for, and while loops, as well as function definition and usage, complemented by clear code examples and a simple practice exercise to compute the sum of two numbers.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Basics: Variables, Data Types, Control Structures, and Functions

Goal : Become familiar with basic Python syntax and data types.

Learning Content : Variables and data types (int, float, str, list, tuple, dict, set), control structures (if, for, while), and function definition and invocation.

Code Examples :

# 整型 (int)
age = 25
print(f"年龄是: {age}")
# 浮点型 (float)
height = 1.75
print(f"身高是: {height}")
# 字符串 (str)
name = "张三"
print(f"名字是: {name}")
# 列表 (list)
fruits = ["苹果", "香蕉", "橙子"]
print(f"水果列表: {fruits}")
# 元组 (tuple)
coordinates = (10, 20)
print(f"坐标: {coordinates}")
# 字典 (dict)
person = {"姓名": "李四", "年龄": 30, "城市": "北京"}
print(f"个人信息: {person}")
# 集合 (set)
colors = {"红", "蓝", "绿"}
print(f"颜色集合: {colors}")
score = 85
if score >= 90:
    print("优秀")
elif score >= 70:
    print("良好")
else:
    print("及格")
# 遍历列表
for fruit in fruits:
    print(fruit)
# 遍历字典
for key, value in person.items():
    print(f"{key}: {value}")
count = 0
while count < 5:
    print(f"计数: {count}")
    count += 1
# 定义一个函数

def add_numbers(a, b):
    """
    计算两个数的和
    :param a: 第一个数
    :param b: 第二个数
    :return: 两数之和
    """
    result = a + b
    return result
# 调用函数
num1 = 10
num2 = 15
sum_result = add_numbers(num1, num2)
print(f"{num1} 和 {num2} 的和是: {sum_result}")

Practice : Write a simple program to calculate the sum of two numbers.

# 定义一个函数来计算两个数的和

def calculate_sum(a, b):
    """
    计算两个数的和
    :param a: 第一个数
    :param b: 第二个数
    :return: 两数之和
    """
    return a + b
# 输入两个数
number1 = float(input("请输入第一个数: "))
number2 = float(input("请输入第二个数: "))
# 计算和
result = calculate_sum(number1, number2)
# 输出结果
print(f"{number1} 和 {number2} 的和是: {result}")

Summary : After completing the exercises, you should be comfortable with Python's basic syntax, data types, control structures, and functions, and will continue to explore more advanced data processing topics in the coming days.

programming fundamentalsFunctionsvariablesbasicscontrol-structures
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.