1.起步
搭建编程环境
Linux、OS X、Windows
(Windows系统下载Python2或Python3 + Pycharm)
>>>print("Hello!")
有C++基础学Pyhon基础语法很轻松啦,哈哈
Python2和Python3语法差别不大
Python需要注意缩进
2.变量 简单数据类型
变量、字符串、数字、注释
name.py
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
message = "Hello, " + full_name.title() + "!"
print(message)
# Say hello to everyone.
print("Hello Python people!")
3.列表
(类似数组)索引从0开始
但可直接使用的函数很多,操作简单快捷。
字符串列表、数值列表
示例
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
too_expensive = 'ducati'
motorcycles.remove(too_expensive)
print(motorcycles)
print("\nA " + too_expensive.title() + " is too expensive for me.")
修改列表元素
a[0]='haha'
添加元素
a.append('haha') #列表末尾
a.insert(0,'haha')#列表中
删除元素
del a[0]
a.pop() #删除末尾
a.pop(0)
a.remove('haha')#根据值删除元素
操作列表
a.sort()#永久性排序
a.sorted()#临时排序
a.reverse()
len(a)
for循环遍历
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
range()创建数值列表
numbers = list(range(1,6))
print(numbers)
min(numbers) #方便的函数
max(numbers)
sum(numbers)
切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
for player in players[:3]:
print(player.title())
b=a[:]#复制列表
元组(不可变的列表)
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
4.字典
示例
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print("Original position: " + str(alien_0['x_position']))
# Move the alien to the right.
# Figure out how far to move the alien based on its speed.
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
# This must be a fast alien.
x_increment = 3
# The new position is the old position plus the increment.
alien_0['x_position'] = alien_0['x_position'] + x_increment
print("New position: " + str(alien_0['x_position']))
del a['haha']##删除
user_0 = {'username': 'efermi', ##遍历
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
avorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " +
language.title() + ".")
嵌套
存储字典的列表
存储列表的字典
存储字典的字典
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())