本文是自己学习python的笔记,并不适合所有人,只是自己认为是知识点,需要随时巩固的。
变量名、函数名、方法名、文件名使用小写字母,单词之间用下划线分隔(_)
字符串:用"或'包起来的字符,"和'之间可以互相包含,可以使用转义符\
方法:
title() 以首字母大写的方式显示每个单词,但是并不改变字符串的内容,除非重新赋值
upper()/lower() 全部显示为大写/小写,也不改变字符串本身
rstrip() 删除尾部的空格(r, right)
lstrip() 删除开头的空格(l, left)
strip() 删除两端的空格
+ 拼接字符串, "hello," + "python"
\n 换行符, \t 制表符
数字:
/ 除法, 结果是小数
// 除法, 结果是整数(向下取整)
% 取模, 余数
** 乘方
浮点数: 浮点数运算的结果的位数是不确定的
str(): 数字与字符串拼接时,需要使用str()函数数字转化为字符串再拼接
python的指导原则: import this
>>> fruits = ['apple', 'banana', 'pear']
>>> print(fruits)
['apple', 'banana', 'pear']
>>> print(fruits[0])
apple
>>> print(fruits[-1])
pear
>>> fruits[0] = 'strawberry'
>>> print(fruits)
['strawberry', 'banana', 'pear']
fruits.append('apple')
fruits.insert(0, 'tomato')
del fruits[0]
f = fruits.pop()
f = fruits.pop(1)
fruits.sort() 会改变list的顺序
fruits.sort(reverse=True) 降序
sorted(fruits) 只按排序显示,不改变list
sorted(fruits, reverse=True) 降序
fruits.reverse() 倒序, 会改变list,再次reverse就回去了
len(fruits) 列表的长度
可使用函数list() 将range() 的结果直接转换为列表。如果将range() 作为list() 的参数,输出将为一个数字列表
numbers = list(range(1,6))
set()可将range()的结果转换为Set
range(起始值, 结束值, 步长)
min(numbers), max(numbers), sum(numbers)
squares = [value**2 for value in range(1,11)] 列表解析
切片 a=squares[2:4] 取第2和第3个
if: and, or, in, not in
==, !=, <, <=, >, >=
if-elif-else
requested_toppings = []
if requested_toppings: # 确定列表是否为空; 空字符串也可以这样判断;in、截取的用法字符串和列表也是类似
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
else:
print("Are you sure you want a plain pizza?")
alien_0 = {'color': 'green', 'points': 5}
alien_0['points'] #获取值
alien_0['x_position'] = 0 #添加键值对
alien_0 = {} #创建空字典
del alien_0['points'] #删除键值对
for key, value in alien_0.items():
print("\nKey: " + key)
print("Value: " + value)
for name in alien_0.keys():
print(name.title())
for name in sorted(alien_0.keys()):
print(name.title() + ", thank you for taking the poll.")
for language in alien_0.values():
print(language.title())
input()获取的值默认是字符串,如果想获取整数,需要使用int()进行转换
while 可使用标记进行条件控制, break退出循环, continue继续
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
while 'cat' in pets:
pets.remove('cat')
传递任意数量的实参(实际为元组) def make_pizza(*toppings):
使用任意数量的关键字实参(实际为键值对) def build_profile(first, last, **user_info):
from xx import yy as zz
from pizza import *
函数指定描述性名称,且只在其中使用小写字母和下划线
class Dog(): # 采用驼峰命名法
def __init__(self, name):
self.name = name #私有属性以两个下划线开头__
在类中,可使用一个空行来分隔方法;而在模块中,可使用两个空行来分隔类。
dog = Dog('Tom')
super().__init__(make, model, year)
模块collections 中的一个类——OrderedDict
from collections import OrderedDict
favorite_languages = OrderedDict()
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'
file_path = '/home/ehmatthes/other_files/text_files/filename.txt'
with open(file_path) as file_object:
try: #try-except-else-finally
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
>>> print('hello' 'python')
hellopython
>>> print('hello', 'python')
hello python
json.dump() 和json.load()
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""测试name_function.py"""
def test_first_last_name(self):
"""能够正确地处理像Janis Joplin这样的姓名吗?"""
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
unittest.main()