变量与数据类型操作
- 变量
(1)变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头。就目前而言,应使用小写的Python变量名。在变量名中使用大写字母虽然不会导致错误,但避免使用大写字母是个不错的主意。
(2)变量名不能包含空格,但可使用下划线来分隔其中的单词
(3)不要将Python关键字和函数名用作变量名,即不要使用Python保留用于特殊用途的单词,如print - 字符串
将name字符串改为全部大写name.upper()
将name字符串改为全部小写name.lower()
将name字符串以首字母大写的方式显示每个单词name.title()
Python使用加号(+)来合并字符串
剔除name字符串开头的空白name.rstrip()first_name = "ada" last_name = "lovelace" full_name = first_name + " " + last_name
剔除name字符串末尾的空白name.lstrip()
剔除name字符串两端的空白name.strip() - 数字
age = 23 ·message = "Happy " + age + "rd Birthday!" print(message) #会报错原因是:Python发现你使用了一个值为整数(int)的变量,但它不知道该如何解读这个值(见)。Python知道这个变量表示的可能是数值23,也可能是字符2和3。 #正解: age = 23 message = "Happy " + str(age) + "rd Birthday!" print(message)
列表操作
列表由一系列按特定顺序排列的元素组成。你可以创建包含字母表中所有字母、数字0~9或所有家庭成员姓名的列表;也可以将任何东西加入列表中,其中的元素之间可以没有任何关系。
- 在Python中,用方括号([])来表示列表,并用逗号来分隔其中的元素。
bicycles = ['trek', 'cannondale', 'redline', 'specialized'] print(bicycles[0]) trek
- 任何列表元素调用字符串方法。
bicycles = ['trek', 'cannondale', 'redline', 'specialized'] print(bicycles[0].title())
- Python为访问最后一个列表元素提供了一种特殊语法。通过将索引指定为-1,这种语法很有用,因为你经常需要在不知道列表长度的情况下访问最后的元素。这种约定也适用于其他负数索引,例如索引-2返回倒数第二个列表元素,索引-3返回倒数第三个列表元素,以此类推。
- 可像使用其他变量一样使用列表中的各个值。
- 要修改列表元素,可指定列表名和要修改的元素的索引,再指定该元素的新值。
列表末尾添加元素 :列表名.append('添加的元素') 在列表中插入元素 :列表名.insert(0, '添加的元素') 从列表中删除元素 :del 列表名[0] /变量名 = 列表名.pop() :法pop()可删除列表末尾的元素,并让你能够接着使用它 ,法pop(0)则可删除第一个元素,以此类推/ 列表名.remove('要删除的元素名')
- 组织列表
name.sort()永久性地修改了name列表元素的排列顺序 name.sort(reverse=True)按与字母顺序相反的顺序排列列表元素 name.sorted()后列表元素的排列顺序并没有改变 name.reverse()反转列表元素的排列顺序 len(列表名)
操作列表
-
遍历整个列表
magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician)
-
创建数字列表
numbers = list(range(1,6)) print(numbers) [1, 2, 3, 4, 5] #使用函数range()时,还可指定步长 even_numbers = list(range(2,11,2)) print(even_numbers) [2, 4, 6, 8, 10]
-
列表解析
squares = [value**2 for value in range(1,11)] print(squares) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
-
切片
name[1:4]提取列表的第2~4个元素
name[:4]没有指定起始索引,Python从列表开头开始提取
name[-3:]提取列表最后三位
同时省略起始索引和终止索引([:])可实现复制列表my_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[:]
(5)Python将不能修改的值称为不可变的,而不可变的列表被称为元组
dimensions = (400, 100)
if语句
-
使用and检查多个条件:都通过了,整个表达式就为True;使用or检查多个条件:只要至少有一个条件满足,就能通过整个测试;检查特定值是否包含在列表中。
>>> requested_toppings = ['mushrooms', 'onions', 'pineapple'] >>> 'mushrooms' in requested_toppings True >>> 'pepperoni' in requested_toppings False 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, you can post a response if you wish. #多个 elif 代码块[仅适合用于只有一个条件满足的情况 if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: price = 10 else: price = 5
-
if语句处理列表。
#检查特殊元素 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 + ".") #确定列表不是空的 requested_toppings = [] if requested_toppings: #使用多个列表 available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', '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 + ".")
字典
-
使用字典
alien_0 = {}alien_0['color'] = 'green'alien_0['points'] = 5 alien_0 = {'color': 'green', 'points': 5} del alien_0['points'] favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', }
-
遍历字典
user_0 = {'username': 'efermi','first': 'enrico','last': 'fermi',}for key, value in user_0.items(): print("\nKey: " + key) print("Value: " + value)>>>Key: lastValue: fermiKey: firstValue: enricoKey: usernameValue: efermi favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } for name in favorite_languages.keys(): print(name.title()) >>> Jen Sarah Phil Edward for language in favorite_languages.values(): print(language.title()) >>> Python C Python Ruby
通过对包含重复元素的列表调用set(),可让Python找出列表中独一无二的元素,并使用这些元素来创建一个集合。
-
嵌套
将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套。pizza = {'crust': 'thick','toppings': ['mushrooms', 'extra cheese'],}# 概述所点的比萨print("You ordered a " + pizza['crust'] + "-crust pizza " +"with the following toppings:")for topping in pizza['toppings']: print("\t" + topping) favorite_languages = { 'jen': ['python', 'ruby'], 'sarah': ['c'], 'edward': ['ruby', 'go'], 'phil': ['python', 'haskell'], } for name, languages in favorite_languages.items(): print("\n" + name.title() + "'s favorite languages are:") for language in languages: print("\t" + language.title()) >>> Jen's favorite languages are: Python Ruby Sarah's favorite languages are: C Phil's favorite languages are: Python Haskell Edward's favorite languages are: Ruby Go