第四章 操作列表

4.3 创建数值列表

练习4.7 创建一个列表,其中包含3~30内能被3整除的数,再使用一个for循环将这个列表中的数打印出来

nums = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
print(nums)
nums_length = len(nums)
for num in range(0, nums_length):
    print(nums[num])

练习4.8:立方 将同一个数乘三次称为立方。例如,在Python中,2的立方用2**3表示。创建一个列表,其中包含前10个整数(1~10)的立方,再使用一个for循环将这些立方数打印出来。

# 使用for生产列表
nums = []
for num in range(1, 11):
    nums.append(num)
# 求立方
nums_length = len(nums)
for num in range(0, nums_length):
    num = (nums[num])
    num_cube = num ** 3
    # 都好分割
    print("数字的立方:", num_cube)
    # f-string
    print(f"数字的立方:{num_cube}")  

练习4.9:立方推导式 使用列表推导式生成一个列表,其中包含前10个整数的立方。

num_cubes = [num ** 3 for num in range(1, 11)]
num_cubes_len = len(num_cubes)
for item in range(0, num_cubes_len):
    print(f"{item + 1}的立方:{num_cubes[item]}")

4.4 使用列表的一部分

players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1:4])
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[2:])
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4])
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:])
['charles', 'martina', 'michael']
['martina', 'michael', 'florence']
['michael', 'florence', 'eli']
['charles', 'martina', 'michael', 'florence']
['michael', 'florence', 'eli']

4.4.2 遍历切片

# 获取列表前三个值,并打印出其值
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]:
    print(player.title())

4.4.3 列表的复制

my_foods = ['pizza', 'falafel', 'carrot cake']
# 利用切片,实现列表的复制
friend_foods = my_foods[:]

print("My favorite foods are:")
print(my_foods)

print("\nMy friend's favorite foods are:")
print(friend_foods)
# 向列表中追加元素,在打印,,确认是两个不同的列表。
my_foods.append("ice tea")
friend_foods.append("ice coffce")

print("\nMy favorite foods are:")
print(my_foods)

print("\nMy friend's favorite foods are:")
print(friend_foods)
My favorite foods are:
['pizza', 'falafel', 'carrot cake']

My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake']

My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice tea']

My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice coffce']

练习5.10

检查用户名 按照下面的说明编写一个程序,模拟网站如何确保每个用户的用户名都独一无二。
• 创建一个至少包含5个用户名的列表,并将其命名为current_users。
• 再创建一个包含5个用户名的列表,将其命名为new_users,并确保其中有一两个用户名也在列表current_users中。
• 遍历列表new_users,检查其中的每个用户名是否已被使用。如果是,就打印一条消息,指出需要输入别的用户名;否则,打印一条消息,指出这个用户名未被使用。
• 确保比较时不区分大小写。换句话说,如果用户名'John'已被使用,应拒绝用户名'JOHN'。​(为此,需要创建列表current_users的副本,其中包含当前所有用户名的全小写版本。​)

代码实现

current_users_lower = []
current_users = ('Rim', 'cate', 'tom', 'lucy', 'Admin')
for user in current_users:
    current_users_lower.append(user.lower())
#
new_users = ('cate', 'Tom', 'Adminn')
if len(current_users_lower) == 0:
    print("We need to find some users!")
else:
    for user in new_users:

        if user.lower() in current_users_lower:
            print(f"the {user} username have in our web system yet, please try other one?")
        else:
            print(f"congratilation u can use the {user} username to login our website")
练习7.5:电影票 有家电影院根据观众的年龄收取不同的票价:不到3岁的观众免费;3(含)~12岁的观众收费10美元;年满12岁的观众收费15美元。请编写一个循环,在其中询问用户的年龄,并指出其票价。
• 使用break语句在用户输入'quit'时退出循环。
prompt = "Tell me how old are you ,I will tell the price of tickets,pls !!!"
prompt += "\nOr you will now be not allow to go to cinime!!!\n"
while True:
    age = input(prompt)
    if age == "quit":
        break
    else:
        age = int(age)
        if age < 3:
            print(f"你现在是{age}岁,你可以免费获得电影票!!!")
        elif age < 12:
            print(f"你现在是{age}岁,你需要10美元获得电影票!!!")
        else:
            print(f"你现在是{age}岁,你需要15美元获得电影票!!!")
• 使用变量active来控制循环结束的时机。
prompt = "Tell me how old are you ,I will tell the price of tickets,pls !!!"
prompt += "\nOr you will now be not allow to go to cinime: \n"

flag = True
while flag:
    age = input(prompt)
    if age == "quit":
        flag = False
    else:
        age = int(age)
        if age < 3:
            print(f"你现在是{age}岁,你可以免费获得电影票!!!")
        elif age < 12:
            print(f"你现在是{age}岁,你需要10美元获得电影票!!!")
        else:
            print(f"你现在是{age}岁,你需要15美元获得电影票!!!")
• 在while循环中使用条件测试来结束循环。
prompt = "Tell me how old are you ,I will tell the price of tickets,pls !!!"
prompt += "\nOr you will now be not allow to go to cinime: \n"
age = " "
while age != "quit":
    age = input(prompt)
    if age != "quit":
        age = int(age)
        if age < 3:
            print(f"你现在是{age}岁,你可以免费获得电影票!!!")
        elif age < 12:
            print(f"你现在是{age}岁,你需要10美元获得电影票!!!")
        else:
            print(f"你现在是{age}岁,你需要15美元获得电影票!!!")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值