python基础总结

爷,独闯天下 提交于 2019-12-09 19:37:35
 
一、环境搭建
python开发集成环境(PyCharm):https://www.jetbrains.com/pycharm/download/#section=windows
Pycharm就是python的开发集成环境,打个比喻就是我们自动化用IDEA来管理项目一样,PyCharm就是一个用来写python语言的工具。
  • 创建工程:
解释器选择就是选择python安装路径
新建文件,.py文件为python文件
右键run之后的结果查看
 
  • 关于代码注释
单行注释格式:#空格 注释内容 ,例子# 这是一条单行注释
多行注释格式:"""多行注释内容"""(六个双引)
例子
"""
这是多行注释
 
"""
多行注释格式:'''多行注释内容'''(六个单引)
  • 变量
在Python中使用变量时,需要遵守一些规则和指南。违反这些规则将引发错误,而指南旨在让你编写的代码更容易阅读和理解。请务必牢记下述有关变量的规则。
  1. 变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头,例如,可将变量命名为message_1,但不能将其命名为1_message。
  2. 变量名不能包含空格,但可使用下划线来分隔其中的单词。例如,变量名greeting_message可行,但变量名greetingmessage会引发错误。
  3. 不要将Python关键字和函数名用作变量名,即不要使用Python保留用于特殊用途的单词,如print 。
  4. 变量名应既简短又具有描述性。例如,name比n好,student_name比s_n好,name_length比length_of_persons_name好。
  5. 慎用小写字母l和大写字母O,因为它们可能被人错看成数字1和0。
要创建良好的变量名,需要经过一定的实践,在程序复杂而有趣时尤其如此。随着你编写的程序越来越多,并开始阅读别人编写的代码,将越来越善于创建有意义的变量名。
注意 就目前而言,应使用小写的Python变量名。在变量名中使用大写字母虽然不会导致错误,但避免使用大写字母是个不错的主意。
python中的变量不需要声明类型,变量被赋值之后类型会自动指定,这也是动态语言的特性之一;
  • 数据类型
  • Python将带小数点的数字都称为浮点数。
  • 字符串输出str(变量),看一下下面例子:
birthday.py
age = 23
message = "Happy " + age + "rd Birthday!"
print(message)
 
预期输出:Happy 23rd birthday! 
实际结果:TypeError: Can't convert 'int' object to str implicitly
这是一个类型错误 ,意味着Python无法识别你使用的信息,Python发现你使用了一个值为整数(int )的变量,但它不知道该如何解读这个值
 
接下里修改为
age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)
 
实际输出:Happy 23rd birthday! 
python中的变量不需要声明类型,变量被赋值之后类型会自动指定,这也是动态语言的特性之一;这句话结合上面的例子应该理解了吧
 
  • 列表
 
由一系列按特定顺序排列的元素组成,用方括号([] )来表示列表,并用逗号来分隔其中的元素
例子:bicycles = ['trek', 'cannondale', 'redline', 'specialized']
列表是有序集合,因此要访问列表的任何元素,只需将该元素的位置或索引告诉Python即可,例如:print(bicycles[0]),索引从0而不是1开始。索引支持负数,索引-2 返回倒数第二个列表元素,索引-3 返回倒数第三个列表元素。
    修改、添加和删除元素
修改元素直接对指定位置进行赋值替换,完成修改操作。看下面的例子:
motorcycles = ['honda', 'yamaha', 'suzuki'] # 原列表
print(motorcycles)# 打印输出查看
motorcycles[0] = 'ducati' # 指定位置赋值
print(motorcycles) # 再次打印
运行之后的结果:
['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']
 
在列表末尾添加元素,方法append() 将元素'ducati' 添加到了列表末尾
motorcycles.append('ducati')
print(motorcycles)
运行结果:['honda', 'yamaha', 'suzuki', 'ducati']
在列表中插入元素,方法insert()可以在任何位置添加新元素
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
运行结果:['ducati', 'honda', 'yamaha', 'suzuki']
在列表中删除元素,使用del语句,使用del 可删除任何位置处的列表元素,条件是知道其索引。
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
运行结果:
['honda', 'yamaha', 'suzuki']
['yamaha', 'suzuki']
在列表删除元素,使用pop()方法,术语弹出 (pop)源自这样的类比:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素。
motorcycles = ['honda', 'yamaha', 'suzuki'] # 首先定义列表motorcycles
print(motorcycles)
popped_motorcycle = motorcycles.pop() # 从这个列表中弹出一个值,并将其存储到变量popped_motorcycle 中
print(motorcycles) # 打印这个列表,以核实从其中删除了一个值
print(popped_motorcycle) # 最后,我们打印弹出的值,以证明我们依然能够访问被删除的值
运行结果:
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki
可以使用pop() 来删除列表中任何位置的元素,只需在括号中指定要删除的元素的索引即可,例如:last_owned = motorcycles.pop(0),这样将会删除类表第一个元素。
使用remove() 从列表中删除元素时,也可接着使用它的值。注意 方法remove() 只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值。
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
too_expensive = 'ducati'
motorcycles.remove(too_expensive)
print(motorcycles)
方法sort() 让你能够较为轻松地对列表进行排序,按字母顺序进行排序,还可以按与字母顺序相反的顺序排列列表元素,为此,只需向sort() 方法传递参数reverse=True
按字母顺便排序,假设所有字母都是小写
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
运行结果:['audi', 'bmw', 'subaru', 'toyota']
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)
运行结果:['toyota', 'subaru', 'bmw', 'audi']
方法sorted() 让你能够按特定顺序显示列表元素,同时不影响它们在列表中的原始排列顺序。注意,调用函数sorted() 后,列表元素的排列顺序并没有变。如果你要按与字母顺序相反的顺序显示列表,也可向函数sorted() 传递参数reverse=True
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
运行结果:
Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']
Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']
 Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']
注意 在并非所有的值都是小写时,按字母顺序排列列表要复杂些。决定排列顺序时,有多种解读大写字母的方式,要指定准确的排列顺序,可能比我们这里所做的要复杂。然而,大多数排序方式都基于本节介绍的知识。
方法reverse(),反转列表元素的排列顺序
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)
注意,reverse() 不是指按与字母顺序相反的顺序排列列表元素,而只是反转列表元素的排列顺序:
运行结果:
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']
方法reverse() 永久性地修改列表元素的排列顺序,但可随时恢复到原来的排列顺序,为此只需对列表再次调用reverse() 即可
len() 可快速获悉列表的长度
>>> cars = ['bmw', 'audi', 'toyota', 'subaru']
>>> len(cars)
  • 列表切片(players函数)
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3]) # 打印['charles', 'martina', 'michael']
如果你没有指定第一个索引,Python将自动从列表开头开始,未指定最后的索引,默认一直取到结束
遍历切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]:
    print(player.title())
  • 复制列表
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
 
  • 元组
Python将不能修改的值称为不可变的 ,而不可变的列表被称为元组。
for循环遍历元组
dimensions = (200, 50)
for dimension in dimensions:
    print(dimension)
  • 集合
 
  • 字典
字典 是一系列键—值对 。每个键 都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何Python对象用作字典中的值。键—值 对是两个相关联的值。指定键时,Python将返回与之相关联的值。键和值之间用冒号分隔,而键—值对之间用逗号分隔。例子alien_0 = {'color': 'green', 'points': 5}
    • 访问字典中的值
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, 'y_position': 25, 'x_position': 0}
    • 删除键—值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0) #打印 {'color': 'green'}
    • 遍历所有的键—值对
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
        print("\nKey: " + key)
        print("Value: " + value)
    • 遍历字典中的所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys():
        print(name.title())
    • 遍历字典中的所有值
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())
 
  • 字典嵌套
在类表中嵌套字段
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)
在字典中存储列表
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)
字典嵌套字典
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())
 
 
  • if语句
简单的if 语句
最简单的if 语句只有一个测试和一个操作
if conditional_test:
        do something
如果条件测试的结果为True ,Python就会执行紧跟在if 语句后面的代码;否则Python将忽略这些代码。
 
if-else 语句 
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
        if car == 'bmw':
                print(car.upper())
        else:
                print(car.title())
Python中检查是否相等时区分大小写.
 
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.")
 
使用多个elif 代码块
age = 12
if age < 4:
        price = 0
elif age < 18:
        price = 5
elif age < 65:
        price = 10
else:
        price = 5
print("Your admission cost is $" + str(price) + ".")
 
省略else 代码块
age = 12
if age < 4:
        price = 0
elif age < 18:
        price = 5
elif age < 65:
        price = 10
elif age >= 65:
        price = 5
print("Your admission cost is $" + str(price) + ".")
 
测试多个条件
if-elif-else 结构功能强大,但仅适合用于只有一个条件满足的情况:遇到通过了的测试后,Python就跳过余下的测试。这种行为很好,效率很高,让你能够测试一个特定的条件,然而,有时候必须检查你关心的所有条件。在这种情况下,应使用一系列不包含elif 和else 代码块的简单if 语句。在可能有多个条件为True ,且你需要在每个条件为True时都采取相应措施时,适合使用这种方法。
 
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 pizza!")
 
确定列表不是空的
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?")
 
  • for循环
例子:
magicians = ['alice', 'david', 'carolina']
for magician in magicians: # 这行代码让Python从列表magicians 中取出一个名字,并将其存储在变量magician 中。最后,我们让Python打印前面存储到变量magician 中的名字。
        print(magician)
 
for循环经常容易犯的错误 1. for循环的语句忘记缩进,不是for循环的语句缩进 2.遗漏了冒号
利用for循环创建列表(函数range())
例子:
for value in range(1,5):
        print(value) # 打印结果 1 2 3 4 
numbers = list(range(1,6))
print(numbers) # 运行结果[1, 2, 3, 4, 5]
even_numbers = list(range(2,11,2))
print(even_numbers) # 运行结果[2, 4, 6, 8, 10] 从2开始每次增加2 直到11(不包括11)结束
 
  • while循环
 
  • 设置代码格式
1.建议每级缩进都使用四个空格,这既可提高可读性,又留下了足够的多级缩进空间
2.建议每行不超过80字符
3.在大多数计算机中,终端窗口每行只能容纳79字符
4.将程序的不同部分分开,可使用空行
 
 
 
 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!