Python 基础

0 配置pip 包库映像地址【以清华为例】

文件路径及文件名:C/user/Username/pip/pip.ini

文件内容:

 

1 字符串相关函数

  • .title() # 将字符串每个单词的首字母大写
  • .upper() #不改变字符串变量的值
  • .lower() #不改变字符串变量的值
  • f"{var} ,字符串" # 将变量和字符串格式化
  • .rstrip() # 去除字符串尾空格,暂时的,再次访问还原
  • .lstrip() # 去除字符串头空格
  • .strip() # 去除字符串 头和尾的空格
  • .split() # 以空格 将字符串拆分成列表

2 计算符号

  • 3**2  # 9 3的2次方
  • 1_000_0000 # 大数可以使用_分割 不会影响

3 import this #Python之禅

4 列表

特定顺序排列元素组成;元素间可无关系(不必同类型);索引从0开始;-1表示最后一个元素;

  • .append() # 列表末尾添加元素
  • .insert(index,var) # 在index处插入一个值,后面依次右移
  • del list[index] # 删除index索引处元素,后面依次左移
  • .pop() # 删除列表尾一个元素
  • .pop(index) # 删除index处元素
  • .remove(var) # 删除列表中第一出现的var
  • .sort() # 按照字母表顺序,大小排序;永久性;字母数字不可混合排序;
  • sorted(list) # 临时排序,再次访问还原
  • .reverse() # 反转列表顺序
  • len(list) # 确定列表长度
  • 遍历列表
# 依据冒号和缩进

for var in list:

print(var)
  • range 创建数值列表
# 1 2 3 4 ;range(m,n) 最后m到n-1;
  • for value in range(1,5):
print(value)
  • var_list=list(range(1,5))
print(var_list)
  • range(2,11,2)
#从2开始,不断加2,一直达到或者超过11
  • 列表解析
squares=[value**2 for value in range(1,11)]

print(squares)

# 输出 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  • list[0:3] # 返回索引0 1 2 元素
  • list[:4] # 返回前4个元素
  • list[2:] # 返回第三个到最后一个元素
  • list[-2:] # 返回倒数两个元素
  • list[:] #复制列表;如果是list2=list1,只是将list2指针指向list1,并没有真正复制创建一个新list
  • 检查一个值在不在列表中
var_list=["nihao","nihaoa","nizhendehao"]

"nihao" in var_list

"nibuhao" not in var_list

5 元组

  • 不可变的列表
  • 定义 ,严格的说元组是由逗号标识的,定义只包含一个元素的元组,也必须在这个元素后面加上逗号,所以 dimensions=200,50 也是可以的
dimensions=(200,50) #元组使用圆括号

print(dimensions[0])
  • 修改元组变量,虽然不能修改元组的元素,但是可以给存储元组的变量重新赋值
dimensions[0]=250 # 这个是错误的

dimensions=(250,50) # 这个是合法的

6 字典

  • 字典是一系列键值对,与键相关联的值可以是数、字符串、列表乃至字典等任意一个Python对象。
var_dic={'color':'green','point':5} # 创建字典

print(var_dic['color'])
  • 添加
var_kong_dic={} # 创建一个空的字典

var_kong_dic['nihao']="nihao" # 在字典中添加键值对

var_kong_dic['nibuhao']="nibuhao"

print(var_kong_dic)
  • 修改
var_kong_dic['nihao']="How are you?" # 修改值

print(var_kong_dic)
  • 删除
del var_kong_dic['nibuhao'] #删除键值对

print(var_kong_dic)
  • 获取
point_value=var_kong_dic.get('point',"No point value assigned")

#直接打印字典不存在键值报错,get不存在时返回第二个参数;没有指定第二个参数返回None

print(point_value)
  • 遍历
# 添加几个值做演示

var_kong_dic['cnihaos']="nihao"#在字典中添加键值对

var_kong_dic['anihaoss']="nihao"#在字典中添加键值对

 

for k,v in var_kong_dic.items():

    print("Key:"+k)

    print("Value:"+v)
  • 获取字典 键的 列表 # 同样的,值 values
print(var_kong_dic.keys())

print(type(var_kong_dic.keys()))
  • 排序遍历
for name in sorted(var_kong_dic.keys()):

print(name)
  • 删除重复遍历
for var_values in set(var_kong_dic.values())

print(var_values)
  • 区别 集合
# 集合 不会以特定的顺序存储元素

var_jihe={'python','java','C#'}

print(var_jihe)

字典 列表
alien_0={'color':'green','points':5}

alien_1={'color':'red','points':10}

alien_2={'color':'yellow','points':15}

 

aliens=[alien_0,alien_1,alien_2]

print(aliens)

7 函数相关

  • input函数
    • 让程序暂停运行,等待用户输入并将用户输入赋值给一个变量,其参数是向用户显示的提示
message=input("Pleaseinputsomething:")

print(message) # input获取的都是字符串类型
  • 强制类型转换
age=input("Howoldareyou?\n")

print(type(age))

print(":"+age)

 

age=int(age) # 强制类型转化

print(type(age))

print(":"+str(age)) # 输入字符串+数字会报错,所以还需要再来一次类型转换
  • 传递任意数量的实参

形参中的 * 让Python创建一个空元组(不可变),并将收到的所有值都封装在这个元组中、

defmake_pizza(*toppings):

""""打印顾客所点的所有配料"""

print(toppings)

print(type(toppings))

 

make_pizza('peperoni')

make_pizza('mushrooms','greenpepers','extracheese')
  • 使用任意数量的关键字实参
    • 形参中的 ** 让Python创建一个空字典,将所有名称值对都放在字典中
defbuild_profile(first,last,**user_info):

"""创建一个字典,其中包含我们知道的有关用户的一切"""

user_info['first_name']=first

user_info['last_name']=last

returnuser_info

 

user_profile=build_profile('albert','einstein',location='princeton',field='physics')

print(user_profile)

8 读取/写入 文件

  • 读取整个文件
#原文件中的换行会被读取,但是打印末尾会多一个空行,因为read() 到达文件末尾时会返回一个空字符串,而将这个空字符串显示出来就是一个空行,如果要去除空行,就在字符串末尾加一个  rstrip()

with open("pi.txt") as file_object:

contents=file_object.read()

print(contents)
  • 逐行读取
#逐行读取每行末尾都会有一个换行符,所以需要加一个rstrip去除

with open("pi.txt") as file_object:

    for line in file_object:

        print(line.rstrip())
  • 创建一个包含文件各行内容的列表
with open("pi.txt") as file_object:

    lines=file_object.readlines()

 

print(type(lines))

print(lines)

 

print("\n")

for line in lines:

    print(line.rstrip())
  • 写入空文件
# 这样会覆盖掉原文件中的内容,打开文件时的w参数,a 附加模式(在文件末尾添加不会覆盖原内容),r+读写模式,省略参数默认r 只读模式

with open("pi.txt",'w') as file_object:

    file_object.write("I love programming.")

 

with open("pi.txt",'a') as file_object:

    file_object.write("\nI love programming,too.")
  • json 存储与读取
import json

 

numbers=[2,3,4,5,6,9]

 

# 存储

filename='numbers.json'

 

with open(filename,'w') as f:

    json.dump(numbers,f)

 

f.close()

 

# 读取

file_name2='numbers.json'

 

#异常处理

try:

    with open(file_name2,'r') as f:

        read_number=json.load(f)

except FileNotFoundError:

    print("The file is not found!")

else:

    print(read_number)

    print(type(read_number))

9 测试

  • 测试函数
    • name_function.py
def get_formatted_name(first,last,middle=''):

    """形参中指定默认值得形参 middle只能放在最后"""

    if middle:

        full_name=f"{first}.{middle}.{last}"

    else:

        full_name=f"{first}.{last}"

    return full_name
  • test_name_function.py
import unittest

 

# 导入单元测试

from name_function import get_formatted_name

 

class NameTestCase(unittest.TestCase):

    """继承 unittest.TestCase"""

    def test_first_last_name(self):

        """方法名必须test打头,这样才能自动运行"""

        formaated_name=get_formatted_name("jone","json")

        self.assertEqual(formaated_name,"jone.json")

        """断言方法"""

 

    def test_test_first_last_middle_name(self):

        formatteed_name=get_formatted_name("A","B","C")

        self.assertEqual(formatteed_name,"A.B.C") # 形参顺序不对会报错的

 

if __name__=='__main__':

    unittest.main()
  • 测试类
    • survey.py
class AnonymousSurvey:

 

    """构造函数"""

    def __init__(self,question):

        """存储 问题和 答案的变量"""

        self.question=question

        self.responses=[]

 

    """显示调查问卷"""

    def show_question(self):

        print(self.question)

 

    """存储单份调查问卷"""

    def store_response(self,new_response):

        self.responses.append(new_response)

 

    """显示所有答案"""

    def show_results(self):

        print("Survey Results:")

        for var_response in self.responses:

            print(f"-{var_response}")
  • test_survey.py
  • # 导入单元测试
    
    import unittest
    
    # 导入测试的类文件
    
    from survey import AnonymousSurvey
    
     
    
    class TestAnonymousSurvey(unittest.TestCase):
    
     
    
        """使用setUp函数 创建一个所有方法都可以使用的类和答案列表"""
    
        def setUp(self):
    
            question="What language did you first learn to speak?"
    
            self.my_survey=AnonymousSurvey(question)
    
            self.responses=['English','Chinese','Janpanese']
    
     
    
        def test_store_single_reponse(self):
    
            self.my_survey.store_response(self.responses[0])
    
            self.assertIn(self.responses[0],self.my_survey.responses)
    
     
    
        def test_store_three_reponses(self):
    
            for reponse in self.responses:
    
                self.my_survey.store_response(reponse)
    
            for reponse in self.responses:
    
                self.assertIn(reponse, self.my_survey.responses)
    
     
    
    if __name__=='__main__':
    
        unittest.main()
posted @ 2021-07-18 18:47  未名w  阅读(76)  评论(0编辑  收藏  举报