Python学习笔记04-字典和用户输入和 while 循环

来源:互联网 发布:js遍历a标签 编辑:程序博客网 时间:2024/06/04 20:00

一个简单的字典

alien = {'color': 'green', 'points': 5}print(alien['color'])print(alien['points'])green5

增加字典

alien['animal'] = 'dog'

创建一个空字典

alien_0 = {}alien_0['color'] = 'green'alien_0['points'] = 5print(alien_0){'color': 'green', 'points': 5}修改alien_0['color'] = 'yellow'

删除字典

del alien_0[‘color’]

取出字典

user_0 = {'username': 'efermi','first': 'enrico','last': 'fermi',}for key, value in user_0.items(): print("\nKey: " + key) print("Value: " + value)

取出键

for key in user_0.keys(): print("\nKey: " + key) 

取出值

for  value in user_0.values(): print("Value: " + value)

在字典中存储字典

users = {'aeinstein': {'first': 'albert','last': 'einstein','location': 'princeton',},'mcurie': {'first': 'marie','last': 'curie','location': 'paris',},} for username, user_info in users.items(): print("\nUsername: " + username) full_name = user_info['first'] + " " + user_info['last']location = user_info['location'] print("\tFull name: " + full_name.title())print("\tLocation: " + location.title())

函数 input() 的工作原理

message = input("Tell me something, and I will repeat it back to you: ")prompt += "\nWhat is your first name? "print(message)

使用 while 循环

current_number = 1while current_number <= 5:    print(current_number)    current_number += 1使用 break 退出循环在循环中使用 continue
原创粉丝点击