学习Python的第三天,我开始深入Python的基本语法和特性,并通过编写一些简单的代码来加深理解。以下是我今天学习的一些代码案例:
1. 函数定义与调用
# 定义一个函数,计算两个数的和
def add_numbers(a, b):
return a + b
# 调用函数
result = add_numbers(5, 3)
print("The sum is:", result)
2. 字符串操作
# 字符串拼接
str1 = "Hello, "
str2 = "World!"
combined_str = str1 + str2
print(combined_str)
# 字符串切片
text = "Python is a powerful language."
substring = text[7:13] # 从索引7到索引12(不包含)
print(substring)
# 查找字符串中的子串
index = text.find("powerful")
if index != -1:
print("Found 'powerful' at index:", index)
else:
print("'Powerful' not found.")
# 字符串替换
new_text = text.replace("language", "programming language")
print(new_text)
3. 文件操作
# 写入文件
with open("example.txt", "w") as file:
file.write("This is an example text.\n")
file.write("Writing to a file in Python is easy.")
# 读取文件
with open("example.txt", "r") as file:
content = file.read()
print(content)
# 逐行读取文件
with open("example.txt", "r") as file:
for line in file:
print(line, end='') # end='' 用于避免额外的换行符
4. 条件语句与循环
# 条件语句
num = 10
if num > 5:
print("The number is greater than 5.")
elif num == 5:
print("The number is equal to 5.")
else:
print("The number is less than 5.")
# 循环语句
for i in range(5):
print(i)
# 使用while循环
count = 0
while count < 5:
print(count)
count += 1
这些代码案例涵盖了第三天学习的一些重要内容,包括函数的定义和使用、字符串操作、文件读写以及条件语句和循环的使用。通过编写和运行这些代码,我能够更好地理解和掌握Python的基本语法和特性。随着学习的深入,我将继续编写更复杂的程序来提升自己的编程能力。