1. 计算阶乘
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
result = factorial(5)
print("5的阶乘:", result)
2. 判断质数
def is_prime(number):
if number < 2:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True
print("7是质数吗?", is_prime(7))
3. 反转字符串
def reverse_string(input_str):
return input_str[::-1]
original_str = "Hello, World!"
reversed_str = reverse_string(original_str)
print("原始字符串:", original_str)
print("反转后字符串:", reversed_str)
4. 计算斐波那契数列
def fibonacci(n):
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
fib_sequence = [0, 1]
while len(fib_sequence) < n:
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence
result = fibonacci(8)
print("斐波那契数列:", result)
5. 列表推导式
numbers = [1, 2, 3, 4, 5]
squared_numbers = [num**2 for num in numbers]
print("原始列表:", numbers)
print("平方后列表:", squared_numbers)
6. 文件操作
# 写入文件
with open("example.txt", "w") as file:
file.write("Hello, Python!\nThis is an example.")
# 读取文件
with open("example.txt", "r") as file:
content = file.read()
print("文件内容:\n", content)
这些实例覆盖了一些基本的编程概念,包括递归、循环、条件语句、列表操作等。你可以根据需要选择并修改这些实例,以适应你的学习和实践需求。
转载请注明出处:http://www.zyzy.cn/article/detail/217/Python3