Python基础必备知识
茴邡 2018-10-30 11:07:35 Python3
title()以首字母大写的方式显示每个单词,即将每个单词的首字母都改为大写
upper() 即将每个单词全部都改为大写
lower() 即将每个单词全部都改为小写
name = "ada lovelace"
print(name.title())f
>>Ada Lovelace
制表符,可使用字符组合\t
换行符,可使用字符组合\n
Python能够找出字符串开头和末尾多余的空白。要确保字符串末尾没有空白,可使用方法
rstrip()
>>flag=’python ’
>>flag
‘python ’
>>flag.rstrip()
‘python’
可以剔除字符串开头的空白,或同时剔除字符串两端的空白。为此,可分别使用方法
lstrip()和strip()
调用函数str(),它让Python将非字符串值表示为字符串。
age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)
>>Happy 23rd Birthday!
>>name=’ hardy ’
>>name.lstrip().rstrip().title()
>>’hardy’
在Python中,用方括号([ ])来表示列表,并用逗号来分隔其中的元素。
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
>>['trek', 'cannondale', 'redline', 'specialized']
Python为访问最后一个列表元素提供了一种特殊语法。通过将索引指定为-1,可让Python返回最后一个列表元素, 这种约定也适用于其他负数索引,例如,索引-2返回倒数第二个列表元素,索引-3返回倒数第三个列表元素,以此类推:
Print(bicycles[-1])
>>specialized
方法append()将元素'ducati'添加到了列表末尾,而不影响列表中的其他所有元素。
motorcycles.append('ducati') #在列表motorcycles最后面添加元素’ducati’
使用方法insert()可在列表的任何位置添加新元素。
motorcycles.insert(0, 'ducati') #在列表motorcycles的0号添加,别的元素向后移动。
使用方法extend()可以在列表后面扩展列表
motorcycles.extend([‘ducati’,’yuan’]) #在列表后面扩展新的两个元素
方法pop()可删除列表末尾的元素,并让你能够接着使用它。同时你可以使用pop()来删除列表中任何位置的元素,只需在括号中指定要删除的元素的索引即可。
p = motorcycles.pop() :变量p里面装着列表motorcycles的最后一个值。
p = motorcycles.pop(0) :变量p里面装着列表motorcycles的0位的值。
如果知道要删除的元素在列表中的位置,可使用del语句删除元素。
del motorcycles[0] :删除列表motorcycles的最前面(0位)元素。
你不知道要从列表中删除的值所处的位置。如果你只知道要删除的元素的值,可使用
方法remove()。注意:方法remove()只删除第一个指定的值。
too_expensive = 'ducati' || 删除列表motorcycles中的元素‘ducati’
motorcycles.remove(too_expensive) ||
使用方法 sort()对列表进行永久性排序.
cars.sort() ||对列表中元素首字母从a到z顺序排列。
按与字母顺序相反的顺序排列列表元素,为此,只需向sort()方法传递参数reverse=True
cars.sort(reverse=True) ||对列表中元素首字母从z到a顺序排列
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
>>['audi', 'bmw', 'subaru', 'toyota']
cars.sort(reverse=True)
print(cars)
>>['toyota', 'subaru', 'bmw', 'audi']
使用函数sorted()对列表进行临时排序,同时还可以用这个函数进行字母顺序相反排列
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(sorted(cars))
print(sorted(cars,reverse=True))
>>['audi', 'bmw', 'subaru', 'toyota']
>> ['toyota', 'subaru', 'bmw', 'audi']字母按照相反的顺序排列
要反转列表元素的排列顺序,可使用方法reverse()
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.reverse()
print(cars)
>>['subaru', 'toyota', 'audi', 'bmw']
使用函数len()可快速获悉列表的长度
>>> cars = ['bmw', 'audi', 'toyota', 'subaru']
>>> len(cars) >>4
For循环
magicians = ['bmw', 'audi', 'toyota', 'subaru']
for magician in magicians: #将magicians中的元素赋值给magician并逐个输出
print(magician) #注意冒号后面要缩进!!!!
Python根据缩进来判断代码行与前一个代码行的关系。
for语句末尾的冒号告诉Python,下一行是循环的第一行。
函数range()让你能够轻松地生成一系列的数字
for value in range(1,5): #不会显示数字5
print(value)
>> 1
2
3
4
创建数字列表,可使用函数list()将range()的结果直接转换为列表。如果将range()作为list()的参数,输出将为一个数字列表。
numbers = list(range(1,6))
print(numbers)
>> [1, 2, 3, 4, 5]
找出数字列表的最大值、最小值和总和
>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45
列表解析
squares = [value**2 for value in range(1,11)]
print(squares)
>>>[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
说明:定义一个表达式,用于生成你要存储到列表中的值。在这个示例中,表达式为value**2,它计算平方值。接下来,编写一个for循环,用于给表达式提供值,再加上右方括号。在这个示例中,for循环为for value in range(1,11),它将值1~10提供给表达式value**2。请注意,这里的for语句末尾没有冒号。
处理列表的部分元素——Python称之为切片
players=['charles','martina','michael','florence','eli']
print(players[0:3]) #players只是一个列表名,并不是一个函数
>>>['charles', 'martina', 'michael']
print(players[:4]) #输出从列表第一个开始位号为4的前一个
print(players[2:]) #输出从列表的位号为2开始到最后一个
print(players[-3:]) #输出从列表的倒数第三个到末尾的元素
遍历列表的部分元素,可在for循环中使用切片。
players=['charles','martina','michael','florence','eli']
for player in players[:3]:
print(player.title())
>>>Charles
Martina
Michael
Python将不能修改的值称为不可变的,而不可变的列表被称为元组,元组看起来犹如列表,但使用圆括号而不是方括号来标识。
像列表一样,也可以使用for循环来遍历元组中的所有值
dimensions = (200, 50)
for dimension in dimensions:
>>>print(dimension)
虽然不能修改元组的元素,但可以给存储元组的变量赋值。因此,如果要修改前述矩形的尺
寸,可重新定义整个元组
dimensions = (200, 50)
print(dimensions)
dimensions = (400, 100)
print(dimensions)
>>>(200,50)
(400,100)
if语句
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars: #注意后面的冒号
if car == 'bmw': #注意后面的冒号
print(car.upper())
else:
print(car.title())
简单的 if 语句
age = 19
if age >= 18:
print("You are old enough to vote!")
>>> You are old enough to vote!
if-else 语句
age = 17
if age >= 18: #冒号
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else: #冒号
print("Sorry, you are too young to vote.")
print("Please register to vote as soon as you turn 18!")
>>>Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!
if-elif-else 结构:依次检查每个条件测试,直到遇到通过了的条件测试。测
试通过后, Python将执行紧跟在它后面的代码,并跳过余下的测试。
age=2
if age<4: price=0 #实施的操作可以放到冒号的后面
elif age<18: price=5
else: price=10
print("Your admission cost is $"+str(price)+'.')
>>> Your admission cost is $0.
使用多个 elif 代码块 程序略
省略 else 代码块
age = 12
if age < 4: price = 0
elif age < 18: price = 5
elif age >= 65: price = 5 #前面省略了else
print("Your admission cost is $" + str(price) + ".")
>>> Your admission cost is $5.
判断特定的值是否已包含在列表中,可使用关键字in
requested_toopings=['mushrooms','onions','pineapple']
num='mushrooms' in requested_toopings
print(num)
>>> True或
requested_toopings=['mushrooms','onions','pineapple']
if 'mushrooms' in requested_toopings:
print('True')
>>>True
确定特定的值未包含在列表中很重要;在这种情况下,可使用关键字not in
requested_toopings=['mushrooms','onions','pineapple']
num='pepperoni' not in requested_toopings
print(num)
>>>True或if语句同上
确定列表不是空的
requested_toppings=[ ]
if requested_toppings: #注意条件表达式是列表名,Python将在列表至少包含一个
else: #元素时返回True,并在列表为空时返回False
简单的字典, 键和值之间用冒号分隔,而键—值对之间用逗号分隔
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
>>>green
5
添加键-值对,
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}
删除键-值对
alien_0 = {'color': 'green', 'points': 5}
del alien_0['points'] #删除字典中的键-值对
遍历所有的键-值对
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi'
}
for key, value in user_0.items(): #方法items()它返回一个键-值对列表
print("Key: " + key)
print("Value: " + value)
>>>Key: last
Value: fermi
Key: first
Value: enrico
Key: username
Value: efermi
不需要使用字典中的值时,方法keys()很有用
for name in favorite_languages.keys(): #方法keys()返回一个键
调用了函数sorted()这让Python列出字典中的所有键,并在遍历前对这个列表进行排序
for name in sorted(favorite_languages.keys()): #对返回的键进行首字母排序
方法values()它返回一个值列表,而不包含任何键
for language in favorite_languages.values():
print(language.title())
剔除重复项,可使用集合(set())
for language in set(favorite_languages.values()):
使用函数input()时,Python将用户输入解读为字符串
name = input("Please enter your name: ") #先打印引号里面的东西,在用户输入
函数int()将数字的字符串表示转换为数值表示
while循环不断地运行,直到指定的条件不满足为止
要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break语句
要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句
函数
def greet_user(): #关键字def函数定义,函数名为greet_user()
print("Hello!") #函数体
greet_user()
传递实参
位置实参
def describe_pet(animal_type, pet_name):
describe_pet('hamster', 'harry')
实参hamster传递给形参animal_type,实参harry传递给形参pet_name
关键字实参
def describe_pet(animal_type, pet_name):
describe_pet(animal_type='hamster', pet_name='harry')
实参hamster传递给形参animal_type,实参harry传递给形参pet_name
传递参数指定默认值
def describe_pet(pet_name, animal_type='dog'): #不传递实参时,形参anumal_type默认时‘dog’
使用return语句将值返回到调用函数的代码行.
Python将非空字符串解读为True
middle_name='' #空字符串
if middle_name: #条件测试语句为假
传递任意数量的实参
下面的函数只有一个形参*toppings,但不管调用语句提供了多少实参,这个形参都将它们统统收入囊中
def make_pizza(*toppings):
make_pizza('pepperoni') #一个形参
make_pizza('mushrooms', 'green peppers', 'extra cheese') #两个形参
形参名*toppings中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中
结合使用位置实参和任意数量实参
如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。 Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。
def make_pizza(size, *toppings):
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
函数编写成能够接受任意数量的键—值对
def build_profile(**user_info): #可以接受任意数量的键-值对
user_profile = build_profile(location='princeton',field='physics') #可以输入键-值对
import语句允许在当前运行的程序文件中使用模块中的代码
导入模块中的特定函数
from module_name import function_name #从模块module_name中调函数fun...
通过用逗号分隔函数名,可根据需要从模块中导入任意数量的函数
from module_name import function_0, function_1, function_2 #从模块中调3个函数
注意:若使用这种语法,调用函数时就无需使用句点
from pizza import make_pizza
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
使用 as 给函数指定别名
如果要导入的函数的名称可能与程序中现有的名称冲突,或者函数的名称太长,可指定简短而独一无二的别名——函数的另一个名称,类似于外号。要给函数指定这种特殊外号,需要在导入它时这样做。
from pizza import make_pizza as mp
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
使用 as 给模块指定别名
import pizza as p
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
导入模块中的所有函数:使用星号(*)运算符可让Python导入模块中的所有函数
from pizza import *