Python基础知识
变量、字符串、数字、数据类型
变量
1、打印20次
>>> print "Hello " * 20
Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello
Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello
2、字符串方法:str()
, upper()
,lower()
, lstrip()
和strip()
, title()
等
3、三重引号字符串(triple-quoted string),
long_string = """Sing a song of sixpence, a pocket full of rye,
Four and twenty blackbirds baked in a pie.
When the pie was opened the birds began to sing.
Wasn't that a dainty dish to set before the king?"""
# or
long_string = '''Sing a song of sixpence, a pocket full of rye,
Four and twenty blackbirds baked in a pie.
When the pie was opened the birds began to sing.
Wasn't that a dainty dish to set before the king?'''
数字与运算符
1、除法/
与 //
在Python2中
>>> print 3/2
1
>>> print 3.0 / 2
1.5
但在Python3 中
>>> print (3/2)
1.5
>>> print (3//2)
1
2、指数 、取余
>>> print 3 ** 5
243
>>> print 7 % 2
1
3、科学计数
>>> a = 2.5e6
>>>
>>> b = 1.2e-7
数据类型
-
float()
从一个字符串或整数创建一个新的浮点数(小数)。 -
int()
从一个字符串或浮点数创建一个新的整数。 -
str()
从一个数(可以是任何其他类型)创建一个新的字符串。 -
type()
可明确地告诉我们变量的类型
>>> a = '44.2'
>>> b = 44.2
>>> type(a)
<type 'str'>
>>> type(b)
<type 'float'>
类型转换错误:如果向
int()
或float()
提供的不是一个数,
列表(数组)
基本方法
1、修改列表元素
motorcycles[0] = 'ducati'
2、在列表中添加元素: append()
、insert()
motorcycles.append('suzuki')
motorcycles.insert(0, 'ducati')
3、从列表中删除元素 : pop()
, remove()
del motorcycles[0]
last_owned = motorcycles.pop()
first_owned = motorcycles.pop(0)
# remove()
motorcycles.remove('ducati')
# or
motorcycles.remove(too_expensive)
4、使用方法sort()对列表进行永久性排序**
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
# or
cars.sort(reverse=True)
5、使用函数sorted()对列表进行临时排序**
sorted(cars)
6、reverse()
方法reverse()
永久性地修改列表元素的排列顺序,但可随时恢复到原来的排列顺序,为此只需对列表再次调用reverse()
即可
7、len()
>>> cars = ['bmw', 'audi', 'toyota', 'subaru']
>>> len(cars)
4
8、索引为-1
时 , 指向最后一项。
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles[-1]) # suzuki
motorcycles = []
print(motorcycles[-1]) # error
遍历列表
使用for item in items:
来遍历 , 另外Python代码通过缩进来识别代码块。
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
print("I can't wait to see your 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!
数值列表
1、range()
for value in range(1,6):
print(value)
# output
# 1
# 2
# 3
# 4
# 5
2、list()
even_numbers = list(range(2,11,2))
print(even_numbers) # [2, 4, 6, 8, 10]
#######################################
squares = []
for value in range(1,11):
square = value**2
squares.append(square)
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#######################################
squares = [value**2 for value in range(1,11)]
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
3、min()
, max()
, sum()
>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45
切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3]) # ['charles', 'martina', 'michael']
print(players[1:4]) # ['martina', 'michael', 'florence']
print(players[:4]) # ['charles', 'martina', 'michael', 'florence']
print(players[2:]) # ['michael', 'florence', 'eli']
print(players[-3:]) # ['michael', 'florence', 'eli']
复制列表
完全复制一个副本。
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
下面的方法仅仅是两个变量的指向相同。
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods
元组
Python将不能修改的值称为不可变的,而不可变的列表被称为元组。
dimensions = (200, 50)
dimensions[0] = 250 # error
# 但可以重新赋值
dimensions = (400, 100) # OK
用户输入
1、使用input()
、 raw_input()
函数来实现用户输入
>>> age = input("How old are you? ")
How old are you? 21
>>> age
'21'
>>> age = int(age)
>>> age >= 18
True
Python 2 中的
raw_input()
在 Python 3 中改名为input()
了 ,
if语句和while语句
if语句
1、每条if
语句的核心都是一个值为True
或False
的表达式,这种表达式被称为条件测试。
2、常用的条件测试的运算符:==
, !=
, >
, <=
, and
, or
, in
, not in
etc.
3、if-else
语句 , 见下面的例子:
4、if-elif-else
结构
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) + ".")
Python中没有
===
?
while语句
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
在语句中使用
break
或continue
字典
字典是一系列键值对
1、使用del
删除特定健
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
2、遍历所有的键值对 --- items()
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
3、遍历字典中的所有键 --- keys()
方法keys()
并非只能用于遍历;实际上,它返回一个列表,其中包含字典中的所有键。
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys():
print(name.title())
# 使用函数sorted()来获得按特定顺序排列的键列表的副本
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
4、遍历字典中的所有值 --- values()
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("The following languages have been mentioned:")
# 使用set()保证值唯一
for language in set(favorite_languages.values()):
print(language.title())
输出结果:
The following languages have been mentioned:
Python
C
Ruby
5、嵌套
- 你可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典
函数
1、使用关键字def
定义函数。使用return
返回值。
def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(animal_type='hamster', pet_name='harry')
"""Comment"""
是被称为文档字符串(docstring)的注释,描述了函数是做什么的。文档字符串用三引号括起,Python使用它们来生成有关程序中函数的文档。- 注意默认参数、参数顺序问题。
- 判断参数是否可选的方法:在函数体内部判断某个参数是否存在。
2、剩余参数
def make_pizza(size, *toppings):
"""概述要制作的比萨"""
print("\nMaking a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
3、形参**user_info
中的两个星号让Python创建一个名为user_info
的空字典
模块
导入一个模块:
# 导入整个模块
import pizza
# 导入特定的函数
from module_name import function_0, function_1, function_2
# 使用as给函数指定别名
from pizza import make_pizza as mp
# 导入模块中的所有函数
from pizza import *
类
定义类
class Dog():
"""一次模拟小狗的简单尝试"""
def __init__(self, name, age):
"""初始化属性name和age"""
self.name = name
self.age = age
def sit(self):
"""模拟小狗被命令时蹲下"""
print(self.name.title() + " is now sitting.")
def roll_over(self):
"""模拟小狗被命令时打滚"""
print(self.name.title() + " rolled over!")
def update_name(self,name):
self.name = name
# 使用
my_dog = Dog('willie', 6)
# 直接修改属性的值
my_dog.name = "Mike"
# 通过方法修改属性的值
my_dog.update_name('Mike')
python2中必须加入object参数
class Class(object):
--snip--
继承
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self, make, model, year):
"""初始化父类的属性"""
super(ElectricCar, self).__init__(make, model, year)
# python3 的写法
# super().__init__(make, model, year)
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
注意Python3的写法与Python2不一致
导入类
# 可在一个模块中car.py存储多个类,如Car1 Car2
# 然后从一个模块中导入多个类
from car import Car1 , Car2
# 或导入整个模块
import car
# 又或导入模块中的所有类
from module_name import *
操作文件
读文件
############################ 读取整个文件 ###########################
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
############################ 逐行读取 ###########################
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
####################### 创建一个包含文件各行内容的列表 #######################
filename = 'pi_30_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(pi_string)
print(len(pi_string))
rstrip()
删除(剥除)字符串末尾的空白
写文件
filename = 'programming.txt'
with open(filename, 'a') as file_object:
file_object.write("I also love finding meaning in large datasets.\n")
file_object.write("I love creating apps that can run in a browser.\n")
可指定读取模式(
'r'
)、写入模式('w'
)、附加模式('a'
)或让你能够读取和写入文件的模式('r+'
)
使用json模块存储数据
使用json模块中的
json.dump()
和json.load()
方法。
写入number.json
数据
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as file_object:
json.dump(numbers, file_object)
读json文件
import json
filename = 'username.json'
with open(filename) as f_obj:
username = json.load(f_obj)
print("Welcome back, " + username + "!")
异常处理
def count_words(filename):
"""Count the approximate number of words in a file."""
def count_words(filename):
"""Count the approximate number of words in a file."""
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
pass
else:
# Count approximate number of words in the file.
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
count_words(filename)
常见异常类型:
ZeroDivisionError
、FileNotFoundError
、TypeError
等
注意:try-except
和try-except-else
结构 ????
测试
使用模块unittest
中的工具来为函数和类编写测试。
参考
反馈与建议
- 您可通过 该链接 查看所有的文章。
- 也可通过 GitHub issues 或通过 简书 评论这篇文章,希望能留下您宝贵的建议。
- 如有任何问题,您可以通过邮箱 @liguwe@qq.com 或微博 @August008 联系我。