吐血整理!Python 基础知识大全

变量和简单数据类型

变量
变量的命名:
①变量名只能包含字母、数字和下划线,变量名可以以字母或下划线开头,但不能以数字开头。
②不能将Python关键字和函数名用作变量名。
字符串
字符串就是一系列字符,Python 中,用引号括起来的都是字符串,引号可以是单引号或者双引号。
使用方法修改字符串的大小写:
title()以首字母大写的方式显示每个单词,即将每个单词的首字母都改为大写。
upper()将字符串的每个字母都转换成大写。
lower()将字符串的每个字符都转换为小写。
拼接字符串:
Python 使用加号(+) 来合并字符串。

first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name) #ada lovelace

添加空白和删除空白:
\t制表符
\n换行符
rstrip()删除字符串末尾多余的空格。
lstrip删除字符串开头多余的字符。
strip删除字符串两端的空格。
数字
整数:可以对整数执行+ - * /运算,两个乘号**表示乘方。
浮点数:Python 将带小数点的数字都称为浮点数。
注:在字符串中使用整数时,需要先将整数转换为字符串。

例如:想要输出 Happy 18th Birthday,需要先将 age 转化成字符串类型
age = 18
message = "Happy " + str(age) + "th Birthday"
print(message) #Happy 18th Birthday

列表

列表是由一系列按特定顺序排列的元素组成,可以包含字母、数字以及任何东西,用方括号[]来表示列表,并用逗号来分隔其中的元素。
1.访问列表元素:列表名[索引]
2.在列表末尾添加元素:列表名.append(“元素值”)
3.在列表中插入元素:列表名.insert(索引,“元素值”)
4.使用 del 删除列表元素:del 列表名[索引]
5.使用 pop 删除列表元素:方法 pop() 可以删除列表末尾的元素,并能接着使用它。例如:

list1 = ["a","b","c"]
list_pop = list1.pop()
print(list_pop) #c
print(list1) #['a', 'b']

实际上,可以使用 pop() 方法弹出列表中任何位置处的元素,被弹出的元素不再在列表中了,即删除任何位置的元素,只需在括号中指定要删除的元素的索引。

删除元素使用 del 还是 pop() :
如果要从列表中删除一个元素,且不再以任何方式使用它,就用 del 语句;如果要在删除元素后还能继续使用它,就用 pop() 方法。

6.根据值删除元素:当不知道要删除的元素在列表中的位置,只知道要删除元素的值时,可使用方法remove()
列表名.remove(“要删除元素的值”)

方法remove()只删除第一个指定的值,如果要删除的值可能在列表中出现多次,就要用循环来判断是否删除了所有这样的值。

7.使用 sort() 方法对列表进行永久性的排序:列表名.sort() ,使用这种方法永久性的修改了列表元素的顺序。
8.使用 sorted() 方法对列表进行临时性的排序,sorted(cars) ,可以保留列表元素原来的顺序,同时能够按照特定顺序显示列表元素。
9.列表逆序:列表名.reverse()
10.列表长度:len(列表名)
11.遍历列表:

animals = ["dog", "cat", "pig"]
for animal in animals:
    print(animal.title() + ",it's cute!")
print("I like them")
'''输出结果
Dog,it's cute!
Cat,it's cute!
Pig,it's cute!
I like them
'''

12.创建数值列表
使用 range() 函数可以轻松的生成一系列的数字,例如:

for i in range(1, 6):
    print(i)
'''输出结果
1
2
3
4
5 (前闭后开)
'''

使用 list() 函数可以直接将 range() 的结果转换为列表,例如:

numbers = list(range(1, 6))
print(numbers)
'''输出结果
[1, 2, 3, 4, 5]
'''

使用函数 range() 时,还可以指定步长,例如下面的代码打印1~10内的偶数:

evenNumbers = list(range(2, 11, 2))
print(evenNumbers)
'''输出结果
[2, 4, 6, 8, 10]
'''

对数字列表进行计算:

digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(max(digits))
print(min(digits))
print(sum(digits))
'''输出结果
9
0
45
'''

13.列表切片

animals = ["dog", "cat", "pig", "monkey", "bird"]
print(animals[0:3]) #['dog', 'cat', 'pig']
print(animals[:4]) #没有指定第一个索引,默认从索引为0开始 ['dog', 'cat', 'pig', 'monkey']
print(animals[2:]) #没有指定第二个索引,默认到列表末尾结束 ['pig', 'monkey', 'bird']
print(animals[-3:]) #负数索引返回离列表末尾相应距离的元素 ['pig', 'monkey', 'bird']

14.遍历切片
如果要遍历列表的部分元素,可在 for 循环中使用切片。

for animal in animals[:3]:
    print(animal.title())
'''输出结果
Dog
Cat
Pig
'''

15.复制列表
①要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引。这样可以得到两个列表,如下:

animals = ["dog", "cat", "pig", "monkey", "bird"]
animals2 = animals[:]

animals.append("snake")
animals2.append("mouse")
# 添加元素,两个列表的值不同
print(animals) #['dog', 'cat', 'pig', 'monkey', 'bird', 'snake']
print(animals2) #['dog', 'cat', 'pig', 'monkey', 'bird', 'mouse']

②直接将列表赋值给新列表

animals = ["dog", "cat", "pig", "monkey", "bird"]
animals2 = animals

animals.append("snake")
animals2.append("mouse")
# 添加元素,两个列表元素一样
print(animals)
print(animals2)

元组

列表是可以修改的,但有时候需要创建一系列不可修改的元素,元组可以满足这种需求。Python 将不能修改的值称为不可变的,不可变的列表被称为元祖。使用圆括号来标识。

dimensions = (200, 50)
# 访问元组中的元素
print(dimensions[0]) #200
print(dimensions[1]) #50
# 遍历元组中的值
for dimension in dimensions:
    print(dimension) # 200 50
#修改元组变量
dimensions = (400, 100)
for dimension in dimensions:
    print(dimension) # 400 100

if语句

用 if 语句检查程序的当前状态,并采取相应的措施。

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 65:
    price = 10
else:
    price = 15
print("age:" + str(age) + ", price:" + str(price)) #age:12, price:5

字典

字典是一系列的键值对,每个键都与一个值相关联,可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典,也就是可以将 Python 中的任意对象用作字典中的值。键和值之间用冒号分隔,而键值对之间用逗号分隔。

animals = {'No1':'dog', 'No2':'cat', 'No3':'pig'}
# 访问字典中的值
print(animals['No2']) # cat
# 添加键值对
animals['No4'] = 'monkey'
animals['No5'] = 'snake'
print(animals) # {'No1': 'dog', 'No2': 'cat', 'No3': 'pig', 'No4': 'monkey', 'No5': 'snake'}
# 修改字典中的值
animals['No3'] = 'fish'
print(animals) # {'No1': 'dog', 'No2': 'cat', 'No3': 'fish', 'No4': 'monkey', 'No5': 'snake'}
# 删除键值对
del animals['No1']
print(animals) # {'No2': 'cat', 'No3': 'fish', 'No4': 'monkey', 'No5': 'snake'}
# 遍历字典中所有的键值对
for key, value in animals.items():
    print("\nkey: " + key)
    print("value: " + value)
'''
key: No2
value: cat

key: No3
value: fish

key: No4
value: monkey

key: No5
value: snake
'''
#遍历字典中的所有键
for key in animals.keys():
    print(key.title())
'''
No2
No3
No4
No5
'''
#遍历字典中的所有值
for value in animals.values():
    print(value.title())
'''
Cat
Fish
Monkey
Snake
'''

用户输入和while循环

函数input()
函数 input() 可以让程序暂停运行,等待用户输入一些文本。

number = int(input("请输入一个数字:"))
if number % 2 == 0:
    print(str(number) + "是偶数")
else:
    print(str(number) + "是奇数")

while循环
while 循环不断的运行,直到指定的条件不满足为止。

number = 1
while number <= 5:
    print(number)
    number += 1
'''当number大于5时退出循环
1
2
3
4
5
'''

如果要立即退出 while 循环,不再运行循环中余下的代码,可使用 break 语句。如果要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可以使用 continue 语句。

# 使用 break 退出循环
prompt = "Please enter the name of a city:"
while True:
    city = input(prompt)

    if city == "quit":
        break
'''
Please enter the name of a city:Beijing
Please enter the name of a city:Shanghai
Please enter the name of a city:quit

Process finished with exit code 0
'''
# 在循环中使用 continue 返回到循环开头
number = 0
while number < 10:
    number += 1
    if number % 2 == 0:
        continue

    print(number)
'''
1
3
5
7
9
'''

如果要删除列表中所有包含特定值的元素,要删除所有这些元素,应该使用 while 循环。

animals = ['dog', 'cat', 'pig', 'cat', 'cat', 'fish']
print(animals)  # ['dog', 'cat', 'pig', 'cat', 'cat', 'fish']

while 'cat' in animals:
    animals.remove('cat')

print(animals)  # ['dog', 'pig', 'fish']

函数

函数是带名字的代码块,用于完成具体的工作。

# 传递参数无返回值的函数
def sayHello(name):
    print("Hello, " + name)
sayHello('Andy')  #Hello, Andy
# 有返回值的函数
def getName(firstName, lastName):
    return firstName + " " + lastName
print(getName('Andy', 'Liu'))  #Andy Liu
# 返回字典
def buildName(firstName, lastName):
    '''返回一个字典,其中包含名字信息'''
    return {'first':firstName, 'last':lastName}
print(buildName('Andy', 'Liu')) #{'first': 'Andy', 'last': 'Liu'}
# 列表作为函数参数
def users(names):
    for name in names:
        print("Hello, " + name)
names = ['Andy', 'Allen', 'Jay']
users(names)
'''
Hello, Andy
Hello, Allen
Hello, Jay
'''
# 传递任意数量的参数
def getMsg(age, *names):
    print(str(age) + "岁的人有:")
    for name in names:
        print(name)
getMsg(15, 'Andy')
getMsg(18, 'Allen', 'Hannah', 'John')
'''形参名*names中的星号让Python创建一个名为names的空元组,并将收入的值都封装到这个元组中
15岁的人有:
Andy
18岁的人有:
Allen
Hannah
John
'''
# 接收任意数量的键值对
def buildProfile(first ,last, **userInfo):
    '''创建一个空字典,将信息存入'''
    profile = {}
    profile['firstName'] = first
    profile['lasttName'] = last
    for key, value in userInfo.items():
        profile[key] = value
    return profile
userProfile = buildProfile('albert', 'einstein', location = 'princeton', field = 'physics')
print(userProfile)
'''形参名**userInfo中的两个星号让Python创建一个名为userInfo的空字典,并将收入的键值对都封装到这个字典中
{'firstName': 'albert', 'lasttName': 'einstein', 'location': 'princeton', 'field': 'physics'}
'''

函数可以将它们的代码块与主程序分离,即将函数存储在被称为模块的独立文件中,再将模块导入到主程序中。只需编写一条import语句并在其中指定模块名,就可在程序中使用该模块中的所有函数。可以用as给函数指定别名。

我是快斗,欢迎批评指正!

  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值