首页 > 分享 > python入门

python入门

1.在列表中移动元素
例 假设有一个列表,其中包含新注册但还未验证的网站用户;验证这些用户后,如何将他们移到另一个已验证用户列表中呢?

一种办法是使用一个while 循环,在验证用户的同时 将其从未验证用户列表中提取出来,再将其加入到另一个已验证用户列表中

unconfrimed_users={'alice','brian','candance'} confirmed_users=[] while unconfrimed_users: current_user=unconfrimed_users.pop() print('Verifying user: '+current_user.title()) confirmed_users.append(current_user) print('n The following users have been confirmed:') for user in confirmed_users: print(user.title()) 123456789101112

运行结果:
在这里插入图片描述
2.删除包含特定值的所有列表元素
假设你有一个宠物列表,其中包含多个值为’cat’ 的元素。要删除所有这些元素,可不断运行一个while 循环,直到列表中不再包含值’cat’ ,如下所示:

pets=['cat','bird','cat','dog','goldfish'] while 'cat' in pets: pets.remove('cat') print(pets) 12345

当元素cat在列表时,执行remove()语句。
于是有多山个cat就执行多少次删除语句
最后得到一个没有cat元素的列表
[‘bird’, ‘dog’, ‘goldfish’]

3.使用用户输入来填充字典
调查问卷。询问用户姓名和想去的山,再询问用户是否愿意邀请另外的人参加问卷调查。如果回复no 就退出循环。

answers={} flag=True while flag: name=input('nWhat is your name?') answer=input('Which monuntain would u like to go ?') answers[name]=answer repeat=input('Would u like to let another person respond?(yes/no)') if repeat=='no': flag=False print('------------Result-----------') for name,answer in answers.items(): print(name+' wpuld like to go to: '+answer)

12345678910111213141516

运行结果:
在这里插入图片描述
练习
1.熟食店 :创建一个名为sandwich_orders 的列表,在其中包含各种三明治的名字;再创建一个名为finished_sandwiches 的空列表。遍历列 表sandwich_orders ,对于其中的每种三明治,都打印一条消息,如I made your tuna sandwich ,并将其移到列表finished_sandwiches 。所有三明治都制作好后,打印一条消息,将这些三明治列出来。

sandwich_orders=['tuna','sweet','tomato','apple'] finished_sandwichs=[] for i in sandwich_orders: print('i made your '+i+" sandwich") san=sandwich_orders.pop() finished_sandwichs.append(san) for sandwich in finished_sandwichs: print(sandwich) 12345678910

运行结果:
在这里插入图片描述
2.五香烟熏牛肉卖完了 :使用为完成练习7-8而创建的列表sandwich_orders ,并确保’pastrami’ 在其中至少出现了三次。在程序开头附近添加 这样的代码:打印一条消息,指出熟食店的五香烟熏牛肉卖完了;再使用一个while 循环将列表sandwich_orders 中的’pastrami’ 都删除。确认最终的列 表finished_sandwiches 中不包含’pastrami’ 。

sandwich_orders=['tuna','pastrami','pastrami','sweet','tomato','apple','pastrami'] print('we have run out of pastrami sandwichs') while 'pastrami' in sandwich_orders: sandwich_orders.remove('pastrami') print(sandwich_orders) 123456

3.梦想的度假胜地 :编写一个程序,调查用户梦想的度假胜地。使用类似于“If you could visit one place in the world, where would you go?”的提示,并编写一个打印调查 结果的代码块

answers={} flag=True while flag==True: name=input('nWhat is your name ?') answer=input("Where would u travel to ?") answers[name]=answer reply=input('would u ask your friend to take this test? (yes/no)') if reply=='no': flag=False for key,value in answers.items(): print(key+' would like to go to '+value) 1234567891011121314

运行结果:
在这里插入图片描述

相关知识

Python入门习题大全——宠物
Python笔试题
基于python网上宠物在线宠物购物商城系统设计与实现(django框架)研究背景和意义、国内外现状
Python小练习
python运行run在哪
python 练习题
python学习总结day2
基于Python的猫狗宠物展示系统
输出宠物的叫声python
Python爬虫+可视化教学:爬取分析宠物猫咪交易数据

网址: python入门 https://m.mcbbbk.com/newsview221364.html

所属分类:萌宠日常
上一篇: 铲屎官必读!给宠物吃生骨肉前,一
下一篇: 我的几个简便的生食食谱(转)