2023-11-13Python代码练习第一天

数值与序列类型

'''
1.计算并返回斐波那契数列的第几项

# 封装函数 if条件判断语句
def fibonacci(n):
    if n <= 0:  #如果n小于等于0,返回无
        return None
    elif n == 1 or n == 2:  # 如果n等于1或2,返回1
        return 1
    else:  # 其他情况
        a, b = 1, 1
        for _ in range(3, n+1):
            a, b = b, a + b

        return b
n = 12
result = fibonacci(n)
print(f'The {n}th Fibanacci number is: {result}')
'''

'''
2.10 个随机整数的列表,然后计算并输出其中的最大值和最小值
import random  # 导包

lst = [random.randint(1, 100) for _ in range(10)]
max_value = max(lst)  # 赋值给变量
min_value = min(lst)
print(f"The maximum value is: {max_value}")
print(f"The minimum value is: {min_value}")
'''

'''
3.接受一个整数 n 作为参数,返回一个包含 n 个斐波那契数的列表
def fibonacci_list(n):  # 封装函数,再用if条件语句,然后遍历
    fib_list = []
    if n >= 1:
        fib_list.append(1)
    if n >= 2:
        fib_list.append(1)
    for i in range(2, n):
        fib_list.append(fib_list[i-1] + fib_list[i-2])
    return fib_list

n = 10
fibonacci_sequence = fibonacci_list(n)
print(f"The Fibonacci sequence with {n} terms is: {fibonacci_sequence}")
'''

'''
4.求列表平均值
def average(lst):
def average(lst):
    if len(lst) == 0:
        return None
    return sum(lst) / len(lst)

lst = [1,  2, 3, 4, 5]
avg = average(lst)
print(f'The average of the list is: {avg}')
'''

'''
5.遍历输出姓名
students = ('Alice', 'Bob', 'Charlie', 'David', 'Eve')
for student in students:
    print(student)
'''

'''
6.接受一个整数 n 和一个列表作为参数,返回一个新列表,其中包含原始列表中小于 n 的所有元素
def smaller_than_n(n, lst):
    return [x for x in lst if x < n]

n = 5
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
new_lst = smaller_than_n(n, lst)
print(f'The new list with elements smaller than {n} is: {new_lst}')
'''

'''
7.字典循环输出所有水果和价格
fruits = {
    "apple": 2.99,
    "banana": 1.99,
    "orange": 0.99,
    "grape": 3.49,
    "watermelon": 4.99
}

for fruit, price in fruits.items():
    print(f"The price of {fruit} is: {price}")
'''

'''
8.颠倒字符顺序
def reverse_string(s):
    return s[::-1]

s = 'Hello, World!'
reverse_str = reverse_string(s)
print(f'The reversed string is: {reverse_str}')
'''

'''
9.添加新颜色,再遍历全部元素
favorite_colors = {"白色", "蓝色", "黄色"}
favorite_colors.add("绿色")

for color in favorite_colors:
    print(color)
'''

'''
10.新列表包含 A 和 B 中共同的元素
def find_common_elements(A, B):
    common_elements = []
    for element in A:
        if element in B:
            common_elements.append(element)
    return common_elements

list_A = [1, 2, 3, 4, 5]
list_B = [4, 5, 6, 7, 8]

result = find_common_elements(list_A, list_B)
print(result)
'''
posted @ 2023-11-14 15:03  https_L  阅读(6)  评论(0)    收藏  举报