for循环
for item in list_of_item:
print(item)
创建数字列表
numbers = list(range(1,6))
print(numbers)
#[1, 2, 3, 4, 5]
元祖 与列表相似,但元祖是用圆括号来表示
dimensions =(200,50)
print(dimensions[0])
print(dimensions[1])
元组中的元素是不可修改的,但可以给存储元组的变量复制
if-elif-else语句
age = 17
if age < 4:
print('free')
elif age < 18:
print('pay 5 dollars')
else:
print('pay 10 dollars')
# pay 5 dollars
python中字典用{}大括号中的一系列键-值对表示
alien_0 ={'color':'green','points':5}
print(alien_0('color'))
print(alien_0('points'))
#green
#5
向字典中添加元素
alien_0 ={'color':'green', 'points':5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
#{'color':'green', 'points':5}
#{'color':'green', 'points':5,'x_position':0,'y_position':25}
字典中的items()函数
user_0 = {'username': 'efermi',
'first': 'enrico',
'last': 'fermi'}
for key,value in user_0.items():
print('\nKey: ' + key)
print('Value: ' + value)
#Key: username
#Value: efermi
#Key: first
#Value: enrico
#Key: last
#Value: fermi
python中的keys() 函数(在不需要使用字典中的值时,可以采用keys()获取字典中的键)
favorite_languages = {'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python'}
for name in favorite_languages.keys():
print(name.title())
#Jen
#Sarah
#Edward
#Phil
Python中可以采用values()获取字典中的值
favorite_languages = {'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python'}
print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())
#Python
#C
#Ruby
#Python
for language in set(favorite_languages.values()):
print(language.title())
#Python
#Ruby
#C
# 通过对包含重复元素的列表调用set(),可以让python找出列表中独一无二的元素,并使用这些元素创建一个集合
python中字典嵌套字典
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())