美文网首页
Python学习笔记---基本语法

Python学习笔记---基本语法

作者: 白云梦_7 | 来源:发表于2018-08-23 15:28 被阅读0次

    默认缩进量:四个空格
    末尾不用分号,不建议一行多条语句

    变量

    字符串

    ☆ 大小写

    In [175]: strings = 'ADA,Ada,aDA'
    
    In [176]: strings.lower()#字符串均小写
    Out[176]: 'ada,ada,ada'
    
    In [177]: strings.upper()#字符串均大写
    Out[177]: 'ADA,ADA,ADA'
    
    In [178]: strings.title()#字符串首字母大写
    Out[178]: 'Ada,Ada,Ada'
    

    ☆ 删除空白

    In [179]: string = ' python '
    
    In [180]: string.lstrip()#删除左边空白
    Out[180]: 'python '
    
    In [181]: string.rstrip()#删除右边空白
    Out[181]: ' python'
    
    In [182]: string.strip()#删除两边空白
    Out[182]: 'python'
    
    In [183]: string#但没有改变原字符串
    Out[183]: ' python '
    
    In [184]: string = string.strip()#改变了原字符串,重新赋值
    
    In [185]: string
    Out[185]: 'python'
    

    ☆ 合并字符串
    + #左右要是字符串才行

    python之禅

    In [192]: import this
    The Zen of Python, by Tim Peters
    
    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
    

    字符串、元组不可变
    import re #导入正则表达式模块
    变量赋值同生死,按引用传递

    a = [1,2,3]
    b = a
    a.append(4)
    b
    [1, 2, 3, 4]
    

    函数

    isinstance(x,type)
    isinstance(x,(type1,type2))#检查一个对象是否是某个特定类型的实例
    

    元组

    元组拆包
    元组方法 .count(n)
    tuple()转换为元组
    Python 将不能修改的值称为 不可变的 ,而不可变的列表被称为 元组

    列表

    ☆ 添加和移除元素

    In [17]: a = ['foo','bar','baz','wal']
    
    In [18]: a
    Out[18]: ['foo', 'bar', 'baz', 'wal']
    
    In [19]: a.append('wawa')#将元素添加到列表末尾
    In [20]: a
    Out[20]: ['foo', 'bar', 'baz', 'wal', 'wawa']
    
    In [21]: a.insert(1,'red')#将元素插入到列表的指定位置
    In [22]: a
    Out[22]: ['foo', 'red', 'bar', 'baz', 'wal', 'wawa']
    
    In [23]: a.pop(1)#insert的逆运算,移除并返回指定索引处的元素
    Out[23]: 'red'
    
    In [24]: a.insert(1,'foo')
    In [25]: a
    Out[25]: ['foo', 'foo', 'bar', 'baz', 'wal', 'wawa']
    
    In [26]: a.remove('foo')#按值删除匹配到的第一个元素
    In [27]: a
    Out[27]: ['foo', 'bar', 'baz', 'wal', 'wawa']
    
    In [209]: a = ['foo','bar','baz','wal']
    In [210]: del a[0]#按索引删除。如果你要从列表中删除一个元素,且不再以任何方式使用它,就使用 del 语句;如果你要在删除元素后还能继续使用它,就使用方法 pop() 。
    In [211]: a
    Out[211]: ['bar', 'baz', 'wal']
    

    ☆ 合并列表

    In [28]: [4,None,'foo'] + [7,8,(2,3)]#方法一: +
    Out[28]: [4, None, 'foo', 7, 8, (2, 3)]
    
    In [29]: x = [4,None,'foo']
    In [30]: x.extend([7,8,(2,3)])# 方法二: .extend(),快
    In [31]: x
    Out[31]: [4, None, 'foo', 7, 8, (2, 3)]
    

    ☆ 排序
    names.sort(key = len) #永久改变
    names.reverse() #永久改变,倒序
    sorted(names,reverse= True) #临时改变
    ☆ 切片
    l[start:stop] #[start,stop),元素个数stop-start

    In [49]: seq = [7,2,3,7,5,6,0,1]
    
    In [50]: seq
    Out[50]: [7, 2, 3, 7, 5, 6, 0, 1]
    
    In [51]: seq[1:5]
    Out[51]: [2, 3, 7, 5]
    
    In [52]: seq[1:]
    Out[52]: [2, 3, 7, 5, 6, 0, 1]
    
    In [53]: seq[:3]
    Out[53]: [7, 2, 3]
    
    In [54]: seq[-4:]#负数索引从序列的末尾开始切片
    Out[54]: [5, 6, 0, 1]
    
    In [55]: seq[-6:-2]
    Out[55]: [3, 7, 5, 6]
    
    In [56]: seq[::2]
    Out[56]: [7, 3, 5, 0]
    
    In [57]: seq[::-1]#反序,不改变原序列
    Out[57]: [1, 0, 6, 5, 7, 3, 2, 7]
    
    In [58]: seq
    Out[58]: [7, 2, 3, 7, 5, 6, 0, 1]
    
    In [59]: seq.reverse()#原列表逆序
    
    In [60]: seq
    Out[60]: [1, 0, 6, 5, 7, 3, 2, 7]
    

    内置序列函数

    enumerate(some_list) #返回(i,value)
    sorted(set(''))#返回一个由序列中的唯一元素组成的有序列表
    zip()#用于将多个序列中的元素配对,长度由最短的决定,3,2--2,逆:zip(*list)
    reversed()

    if语句

    if-elif-else #也可以不要else,执行一个代码块
    if #如果要运行多个代码块,就使用一系列独立的if语句

    In [309]: alien_color = 'green'
    
    In [310]: if (alien_color == 'green'):
         ...:     print ("You'v got 5 points")
         ...: else:
         ...:     print ("You'v got 10 points")
         ...:
    You'v got 5 points
    

    字典

    In [343]: dict={'first_name':'bai',
         ...:     'last_name':'liu',#记得缩进
         ...:     'age':18,
         ...:     'city':'Guangzhou',
         ...:     }
    In [352]: for key,value in dict.items():#.items()方法遍历所有key-value
         ...:     print ('key:'+ str(key))
         ...:     print ('value:' + str(value) + '\n')
         ...:
    key:first_name
    value:bai
    
    key:last_name
    value:liu
    
    key:age
    value:18
    
    key:city
    value:Guangzhou
    
    
    In [355]: for key in dict.keys():#.keys()方法遍历所有的key,默认也是键,所以可以直接for key in dict:。方法 keys() 并非只能用于遍历;实际上,它返回一个列表,其中包含字典中的所有键,
         ...:     print (key.title())
         ...:
    First_Name
    Last_Name
    Age
    City
    
    

    键是不可变的,不能是列表

    In [84]: d1
    Out[84]: {'a': 'sunny', 'b': 123, 'c': True}
    
    In [85]: 'b' in d1
    Out[85]: True
    
    In [86]: del d1['a'] #按键删除
    
    In [87]: d1
    Out[87]: {'b': 123, 'c': True}
    
    In [88]: d1.pop('b')
    Out[88]: 123
    
    In [89]: d1
    Out[89]: {'c': True}
    
    In [90]: d1[2] = 12334
        ...: d1['3']= 333
    
    In [91]: list(d1.keys())
    Out[91]: ['c', 2, '3']
    
    In [92]: list(d1.values())
    Out[92]: [True, 12334, 333]
    
    In [93]: d1.update({'e':'early'})#update 合并字典
    
    In [94]: d1
    Out[94]: {'c': True, 2: 12334, '3': 333, 'e': 'early'}
    
    从序列类型创建字典
    In [95]: mapping = dict(zip(range(5),reversed(range(5))))
    
    In [96]: mapping
    Out[96]: {0: 4, 1: 3, 2: 2, 3: 1, 4: 0}
    

    集合

    唯一元素组成的无序集(只有键没有值的字典)

    In [123]: a = set([2,2,2,4,5,6])#创建集合方法一:set()
    
    In [124]: b = {2,2,2,3,4,4,}#方法二:{}
    
    In [125]: a | b
    Out[125]: {2, 3, 4, 5, 6}
    
    In [126]: a & b
    Out[126]: {2, 4}
    
    In [128]: a - b
    Out[128]: {5, 6}
    
    In [129]: a ^b#异或
    Out[129]: {3, 5, 6}
    
    In [130]: {1,2,3}.issubset({1,2,3,4,5})#判断子集
    Out[130]: True
    

    列表、集合以及字典的推导式

    注意只是表达式,不要写出print等执行语句
    列表推导式[expr for val in collection if condition]
    字典推导式{key-expr:value-expr for value in collection if condition}
    集合推导式{expr for val in collection if condition}
    嵌套列表推导式{expr for val1 in collection for val2 in val1 if condition}
    生成器表达式sum(expr for val in collection if condition)

    input语句

    input() #解读为字符串
    int()
    str()

    while循环

    while():
    要在遍历列表的同时对其进行修改,可使用 while 循环。

    unconfirmed_users = ['alice', 'brian', 'candace']
    confirmed_users = []
    #  验证每个用户,直到没有未验证用户为止
    # 将每个经过验证的列表都移到已验证用户列表中
    while unconfirmed_users:
        current_user = unconfirmed_users.pop()
        print("Verifying user: " + current_user.title())
        confirmed_users.append(current_user)
    #  显示所有已验证的用户
    print("\nThe following users have been confirmed:")
    for confirmed_user in confirmed_users:
        print(confirmed_user.title())
    
    Verifying user: Candace
    Verifying user: Brian
    Verifying user: Alice
    The following users have been confirmed:
    Candace
    Brian
    Alice
    
    In [373]: p ='Tell me something, and i will repeat it back to yo
         ...: u: \nEnter "quit" to end. '
    
    In [374]: active = True
    
    In [375]: while active:
         ...:     message = input(p)
         ...:     if message == 'quit':
         ...:         active = False
         ...:     else:
         ...:         print (message)
         ...:
    Tell me something, and i will repeat it back to you:
    Enter "quit" to end. wait
    wait
    Tell me something, and i will repeat it back to you:
    Enter "quit" to end. quit
    

    break #不再执行余下代码,退出整个循环
    continue #不再执行余下代码,退出此次循环,继续执行下一次循环

    函数

    ☆定义函数

    def greet_user():#函数名 + () + :
        """显示简单的问候语"""#文档字符串
        print("Hello!")#记得缩进
    greet_user()#函数调用
    
    def greet_user(username):#函数名 + (形参) + :
        """显示简单的问候语"""#文档字符串,也要缩进
        print("Hello " + username.title() + '!')#记得缩进
    greet_user('John')#函数调用,函数名 + (实参)
    

    ☆传递实参
    位置实参 #实参位置要和形参位置完全对应

    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('hamster', 'harry')
    describe_pet('dog', 'willie')
    
    
    I have a hamster.
    My hamster's name is Harry.
    
    I have a dog.
    My dog's name is Willie.
    

    关键字实参 #务必准确指定函数的形参名

    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')
    
    
    I have a hamster.
    My hamster's name is Harry.
    

    默认值
    使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的实参。这让Python依然能够正确地解读位置实参。

    def describe_pet(pet_name, animal_type='dog'):#给形参指定默认值时,等号两边不要有空格:
        """显示宠物的信息"""
        print("\nI have a " + animal_type + ".")
        print("My " + animal_type + "'s name is " + pet_name.title() + ".")
    
    describe_pet('willie')
    

    function_name(l[:])#只传递副本,函数调用结束后不修改原先列表l
    ☆传递任意数量的实参

    def make_pizza(*toppings):#形参名*toppings中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都装封到这个元组中
        """打印顾客点的所有配料"""
        print(toppings)
    make_pizza('pepperoni')
    make_pizza('mushrooms', 'green peppers', 'extra cheese')
    
    ('pepperoni',)
    ('mushrooms', 'green peppers', 'extra cheese')
    

    def make_pizza(size, *toppings): #如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放到最后
    ☆使用任意数量的关键字实参

    def build_profile(first, last, **user_info):#**user_infoPythonuser_info。形参中的两个星号让n创建一个名为的空字典,并将收到的所有名称—值对都封装到这个字典
        """创建一个字典,其中包含我们知道的有关用户的一切"""
        profile = {}
        profile['first_name'] = first
        profile['last_name'] = last
        for key, value in user_info.items():
            profile[key] = value
        return profile
        
    user_profile = build_profile('albert', 'einstein',location='princeton',field='physics')
    print(user_profile)
    
    {'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}
    

    ☆将函数存储在模块中

    import pizza as p
    p.make_pizza(16,'a')
    
    from pizza import make_ pizza as mp#as 别名
    mp(16,'a')
    

    PEP 8(https://www.python.org/dev/peps/pep-0008/ )建议代码行的长度不要超过79字符,这样只要编辑器窗口适中,就能看到整行代码。如果形参很多,导致函数定义的长度超过了79字符,可在函数定义中输入左括号后按回车键,并在下一行按两次Tab键,从而将形参列表和只缩进一层的函数体区分开来。
    如果程序或模块包含多个函数,可使用两个空行将相邻的函数分开,这样将更容易知道前一个函数在什么地方结束,下一个函数从什么地方开始。
    所有的import 语句都应放在文件开头,唯一例外的情形是,在文件开头使用了注释来描述整个程序。

    ☆lambda函数
    仅有单条语句组成,该语句的结果就是返回值
    print (list(map(lambda x: x * 2 + 10, foo)))

    ☆创建类

    class Dog():#根据约定,在Python中,首字母大写的名称指的是类
        """A simple attempt to model a dog."""
        
        def __init__(self, name, age):#类中的函数称为方法。self形参必不可少,还必须位于其他形参的前面。每当我们根据Dog 类创建实例时,都只需给最后两个形参(name 和age )提供值。
            """Initialize name and age attributes."""
            self.name = name#以self为前缀的变量都可供类中的所有方法使用,称为属性
            self.age = age
      
        def sit(self):
            """Simulate a dog sitting in response to a command."""
            print(self.name.title() + " is now sitting.")
    
        def roll_over(self):
            """Simulate rolling over in response to a command."""
            print(self.name.title() + " rolled over!")
            
    
    my_dog = Dog('willie', 6)#我们通常可以认为首字母大写的名称(如Dog)指的是类,而小写的名称(如my_dog)指的是根据类创建的实例。
    your_dog = Dog('lucy', 3)
    
    print("My dog's name is " + my_dog.name.title() + ".")#要访问实例的属性,可使用句点表示
    print("My dog is " + str(my_dog.age) + " years old.")
    my_dog.sit()#调用方法
    
    print("\nMy dog's name is " + your_dog.name.title() + ".")
    print("My dog is " + str(your_dog.age) + " years old.")
    your_dog.sit()
    

    ☆给属性指定默认值

    """A class that can be used to represent a car."""
    
    class Car():
        """A simple attempt to represent a car."""
    
        def __init__(self, manufacturer, model, year):
            """Initialize attributes to describe a car."""
            self.manufacturer = manufacturer
            self.model = model
            self.year = year
            self.odometer_reading = 0#指定默认值
    
        def get_descriptive_name(self):
            """Return a neatly formatted descriptive name."""
            long_name = str(self.year) + ' ' + self.manufacturer + ' ' + self.model
            return long_name.title()
        def read_odometer(self):
            """打印一条指出汽车里程的消息"""
            print("This car has " + str(self.odometer_reading) + " miles on it.")
       
    my_new_car = Car('audi', 'a4', 2016)
    print(my_new_car.get_descriptive_name())
    my_new_car.read_odometer()
    
    2016 Audi A4
    This car has 0 miles on it.
    
    

    ☆修改属性的值
    直接修改属性的值

    class Car():
        --snip--
    my_new_car = Car('audi', 'a4', 2016)
    print(my_new_car.get_descriptive_name())
    my_new_car.odometer_reading = 23
    my_new_car.read_odometer()
    
    2016 Audi A4
    This car has 23 miles on it.
    

    通过方法修改属性的值

    class Car():
        --snip--
        def update_odometer(self, mileage):
            """将里程表读数设置为指定的值"""
            self.odometer_reading = mileage
    my_new_car = Car('audi', 'a4', 2016)
    print(my_new_car.get_descriptive_name())
    my_new_car.update_odometer(23)
    my_new_car.read_odometer()
    
    2016 Audi A4
    This car has 23 miles on it.
    

    通过方法对属性的值进行递增

    class Car():
        --snip--
        def update_odometer(self, mileage):
            --snip--
        def increment_odometer(self, miles):
            """将里程表读数增加指定的量"""
            self.odometer_reading += miles
    my_used_car = Car('subaru', 'outback', 2013)
    print(my_used_car.get_descriptive_name())
    my_used_car.update_odometer(23500)
    my_used_car.read_odometer()
    my_used_car.increment_odometer(100)
    my_used_car.read_odometer()
    
    2013 Subaru Outback
    This car has 23500 miles on it.
    This car has 23600 miles on it.
    

    ☆继承
    父类在前,子类在后,且

    class ElectricCar(Car):#子类括号后要有父类名称
        """电动汽车的独特之处"""
        def __init__(self, make, model, year):
            """初始化父类的属性"""
            super().__init__(make, model, year)#super()
    

    文件和异常

    ☆读取文件
    Python读取文件时,其中的所有文本都解读为字符串。如果你读取的是数字,并要将其作为数值使用,就必须使用函数int()将其转换为整数,或使用float()函数将其转换为浮点数。

    .read() .readline() .readlines()
    read 读取整个文件
    readline 读取下一行
    readlines 读取整个文件到一个迭代器以供我们遍历(读取到一个list中,以供使用,比较方便)

    with open ('1.txt') as file: #使用关键字with,只管打开文件,不用关闭,python会自动在适合的地方关闭
        content = file.read()#一次性读入所有内容,read()在到达文件末尾时会返回一个空字符串,而这个空字符串显示出来就是一个空行
        print (content.rstrip())#rstrip()删除多出的空行
    

    ☆写入文件
    Python只能将字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用函数str()将其转换为字符串格式。

    filename = 'programming.txt'
    with open(filename, 'w') as file_object:#读取模式‘r’,写入模式‘w’,附加模式‘a’,然而,以写入('w')模式打开文件时千万要小心,因为如果指定的文件已经存在,Python将在返回文件对象前清空该文件。
        file_object.write("I love programming.\n")#write()函数不会在你写入的文本末尾添加换行符
        file_object.write("I love creating new games.\n")
    

    ☆异常
    try-except
    try-except-else #依赖于try 代码块成功执行的代码都应放到else 代码块中。
    原理:Python尝试执行try 代码块中的代码;只有可能引发异常的代码才需要放在try 语句中。有时候,有一些仅在try 代码块成功执行时才需要运行的代码;这些代码应放在else 代码块中。except 代码块告诉Python,如果它尝试运行try 代码块中的代码时引发了指定的异常,该怎么办。

    try-except (TypeError,ValueError)#我们把可能发生错误的语句放在try模块里,用except来处理异常。except可以处理一个专门的异常,也可以处理一组圆括号中的异常,如果except后没有指定异常,则默认处理所有的异常。每一个try,都必须至少有一个except
    try-finally#不管try块代码成功与否都能被执行,而不处理任何异常
    try-else#代码只在try块成功执行

    f = open(path,'w')
    try:
         write_to_file(f)
    except:
        print 'Failed'
    else:
        print 'Succeded'
    finally:
        f.close()
    
    filename = 'alice.txt'
    try:
        with open(filename) as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:#如果要失败时一声不吭,就直接pass
        msg = "Sorry, the file " + filename + " does not exist."
        print(msg)
    else:
    # 计算文件大致包含多少个单词
        words = contents.split()#方法split()以指定分隔符(默认所有空字符)将字符串分拆成多个部分,并将这些部分都存储到一个列表中。
        #str.split(str="", num=string.count(str)).#str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。num -- 分割次数
        num_words = len(words)
        print("The file " + filename + " has about " + str(num_words) + " words.")
    

    ☆存储数据
    模块json

    import json
    numbers = [2, 3, 5, 7, 11, 13]
    filename = 'numbers.json'
    with open(filename, 'w') as f_obj:
        json.dump(numbers, f_obj)#存储数据
    
    import json
    filename = 'numbers.json'
    with open(filename) as f_obj:
        numbers = json.load(f_obj)#存入内存
    print(numbers)
    

    相关文章

      网友评论

          本文标题:Python学习笔记---基本语法

          本文链接:https://www.haomeiwen.com/subject/wresiftx.html