!!!注:由于看了好几个好用的Python脚本但是在使用的时候均报错,而好多地方我却看不懂,so解决不了这些报错,so我决定开始学习一下这一门万恶的语言
1、字符串
用引号括起的都是字符串
"This is a string"
'This is also a string'
可在字符串中包含引号和撇号
正确格式:
"Hallo, 'python' world!"
错误示范:
'Hallo, 'python' world!'
修改字符串大小
.title:首字母大写
name="ada lovelace"
print(name.title)
.upper:全部大写
name="ada lovelace"
print(name.title)
合并字符串
Python中用 + 号表示字符串的合并,也叫拼接
first_name="ada"
last_name="lovelace"
full_name=first_name + " " + last_name
print(full_name)
删除空白
favorite_language = "Python "
favorite_language
"Python "
favorite_language.rstrip()
"Python"
2、列表
有一系列按特定顺序排列的元素组成
用[]号表示列表,并用逗号隔开其中的元素
bicycles = ['trik', 'cannondale','redline','specialized']
print(bicycles)
['trik', 'cannondale','redline','specialized']
访问列表元素
python中第一个列表元素的索引为0
bicycles = ['trik', 'cannondale','redline','specialized']
print(bicycles[0])
trik
修改列表元素
motorcycles = ['honda','yamaha','suzuka']
print(motorcycles)
['honda','yamaha','suzuka']
motorcycles = ['honda','yamaha','suzuka']
motorcycles[0] = ['ducati']
print(motorcycles)
['ducati','yamaha','suzuka']
添加列表元素
.append()将元素添加到表格末尾
motorcycles = ['honda','yamaha','suzuka']
motorcycles.append() = ['ducati']
print(motorcycles)
['honda','yamaha','suzuka','ducati']
列表中插入元素
.insert()可添加到任意位置
添加到第一个元素之后
motorcycles = ['honda','yamaha','suzuka']
motorcycles.insert(0,'ducati')
print(motorcycles)
['honda','ducati','yamaha','suzuka']
列表中删除元素
已知元素位置,可用del 语句删除
motorcycles = ['honda','yamaha','suzuka']
del motorcycles[0]
print(motorcycles)
['yamaha','suzuka']
3、循环
magican = ['aline','dacid','carolina']
for magician in magicians:
print(magician)
简单的循环中,python将先读取其中的第一行代码,而python的读取为一次一个值。
因此,在此循环中,python循环3次。
注:Python对列表中的每一个元素都执行循环指定的步骤,而不管有多少元素。
for循环结束后执行操作
magican = ['aline','dacid','carolina']
for magician in magicians:
print(magician.title() + ", that was great trick!")
print("I can't wait to see you next trick, " + magician.title()) + ".\n"
print("Thank you, everyone. That was a great magic show!")
Alice, that was a great trick!
I can't wait to see your next trick, Alice.
David, that was a great trick!
I can't wait to see your next trick, David.
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.
Thank you, everyone. That was a great magic show!
前两个print都执行了3次循环,
最后一个print只执行1次,因为最后一个print没有缩进。
避免缩进错误
在每一个循环中,应都缩进,而循环结束后的语句则不进行缩进
使用range()创建数值列表:
squares = []
for value in range(1,11):
square = value**2
squares.append(square)
print(squares)
4、 if语句:
# 简单示例:
cars = ['audi','bmw','subaru','toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
运行结果:
Audi
BMW
Subaru
Toyota
条件测试:
每条if语句的核心都是一个值为‘True’或‘False’的表达式,这种表达式被称为条件测试。
Python根据条件测试的值为‘True’还是‘False’来决定是否执行if语句中的代码。
如果条件测试的值为‘True,Python就执行紧跟在if语句后面的代码’;如果为‘False,Python就忽略这些代码’。
# 检查特定值是否不包含在列表:
banned_users = ['andrew','carolina','david']
user = 'marie'
if user not in banned_users:
print(user.title() + ",you can post a response if you wish.")
用户'marie'不包含在列表banned_users中,因此,他将看到一条邀请他发表评论的消息:
marise,you can post a response if you wish.
布尔表达式
条件测试的别名,布尔值通常用于记录条件
# 简单的if语句:
age = 19
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
# 条件通过测试,两条print语句均缩进,因此都将执行:
You are old enough to vote!
Have you registered to vote yet?
# 如果这个值小于18,则程序不会有任何输出。
if-else 语句:
# if-else语句类似与简单的if语句,但其中的else语句让你能够指定条件测试未通过时要执行的操作。
age = 17
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorre,you are too young to vote!")
print("Please register to vote as soon as you turn 18!")
代码之所以可执行,因为只存在两种情形:
要么够投票年龄,要么不够。
if-else结构非常适合用于要让python执行两种操作之一的情形。在这种简单的if-else结构中,总是会执行两个操作中的一个。
if-elif-else结构:
age =12
if age <4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
经常需要检查超过两个的情形,为此python提供了if-elif-else结构。
Python只执行
if-elif-else结构中的一个代码块,它依次检查每个条件测试,直到遇到通过了的条件测试。
测试通过后,Python将执行紧跟在它后面的代码,并跳过余下的测试。
简洁版本:
age =12
if age < 4:
price = 0
elif age < 18:
price = 5
else:
price = 10
print("Your admisstion cost is $" + str(price) + ".")
测试多个条件:
requested_toppings = ['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print(".\nFinished making your pizzal!")
检查特殊元素:
requested_toppings = ['mushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry, we are out of green peppers right now!")
else:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizzal!")
确定列表不是空的:
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print(".\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")
在if语句中将列表名用在条件表达式中时,Python将在列表至少包含一个元素时返回True,并在列表为空时返回False。
如果requested_toppings不为空,就运行与前一个示例相同的for循环;
否则,就打印一条消息,询问顾客是否确实要点不加任何配料的普通比萨
使用多个列表:
available_toppings = ['mushrooms','olives','green peppers','pepperoni','pimeapple','extra cheese']
requested_toppings = ['mushrooms','french fries','extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding " + requested_topping + ".")
else:
print("Sorry, we don't have "+ requested_topping + ".")
print(".\nFinished making your pizzal!")
输出结果:
Adding mushrooms.
Sorry, we don‘t have french fries.
Adding extra cheese.
Finished making your pizza!
字典
使用字典
在Python中,字典时一系列键-值对。每个键都与一个值相关联,可以使用键来访问与之相关联的值。
与键相关联的值可以是数字、字符串、列表及至字典。可以将任何Python对象用作字典中的值。
在Python中,字典用放在花括号{}中的一系列键-值对表示:
alien_0 = {'color': 'green', 'points': 5}
键—值对是两个相关联的值。指定键时,Python将返回与之相关联的值。
键和值之间用冒号分隔,而键—值对之间用逗号分隔。在字典中,你想存储多少个键—值对都可以。
访问字典中的值
alien_0 = {'color': 'green'}
print(alien_0['color'])
结果:
green
字典中可包含任意数量的键—值对
添加键-值对:
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, 'y_position': 25, 'x_position': 0}
!!!注意,键—值对的排列顺序与添加顺序不同。
Python不关心键—值对的添加顺序,而只关心键和值之间的关联关系。
创建一个空字典:
alien_0 = {}
alien_0['color'] = 'green'
alien_0['point'] = 5
print(alien_0)
结果:
{'color': 'green', 'points': 5}
修改字典中的值:
alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow' # 将字典中的 color 从 green 修改为 yellow
print("The alien is " + alien_0['color'] + ".")
有趣的例子
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print("Original x-position : " + str(alien_0['x_position']))
# 向右移动外星人
# 据外星人当前速度决定其移动多远
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
# 这个外星人的速度很快
x_increment = 3
# 新位置等于老位置加上增量
alien_0['x_position'] = alien_0['position'] + x_increment
print("New x-position: " + str(alien_0['x_position']))
删除键-值对:
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['color']
print(alien_0)
结果:
{'color': 'green', 'points': 5}
{'points': 5}
嵌套
字典列表
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
结果:
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
创建一个存储外星人的空列表
aliens = []
#创建30个绿色的外星人
for alien_number in range(30):
new_alien = {'color': 'green', 'point': 5, 'speed': 'slow'}
aliens.append(new_alien)
# 显示前5个
for alien in aliens[:5]:
print(alien)
print("...")
# 显示创建了多少外星人
print("Total number of aliens: " + str(len(aliens)))
运行结果:
{'speed': 'slow', 'color': 'green', 'points': 5}
{'speed': 'slow', 'color': 'green', 'points': 5}
{'speed': 'slow', 'color': 'green', 'points': 5}
{'speed': 'slow', 'color': 'green', 'points': 5}
{'speed': 'slow', 'color': 'green', 'points': 5}
...
Total number of aliens: 30
若要修改前几个外星人的颜色等数据:
aliens = []
for alien_number in range(0,30):
new_alien = {'color': 'green', 'point': 5, 'speed': 'slow'}
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
for alien in aliens[0:5]:
print(alien)
print("...")
运行结果:
{'speed': 'medium', 'color': 'yellow', 'points': 10}
{'speed': 'medium', 'color': 'yellow', 'points': 10}
{'speed': 'medium', 'color': 'yellow', 'points': 10}
{'speed': 'slow', 'color': 'green', 'points': 5}
{'speed': 'slow', 'color': 'green', 'points': 5}
...
网友评论