美文网首页
Python基础

Python基础

作者: 晨钟初磬 | 来源:发表于2020-07-13 23:51 被阅读0次
    中途退出
    exit()
    
    使用缩进来标识代码块,而不是使用{}

    空格至少有1个。

    if 5 > 2:
      print("Five is greater than two!")
    
    多行注释"""
    """
    This is a comment
    written in
    more than just one line
    """
    print("Hello, World!")
    
    快速赋值
    x, y, z = "Orange", "Banana", "Cherry"
    
    不能直接用+拼接数字和字符串
    x = 5
    y = "John"
    print(x + y)#ERROR
    
    内置数据类型
    类型 标识
    Text Type: str
    Numeric Types: int, float, complex
    Sequence Types: list, tuple, range
    Mapping Type: dict
    Set Types: set, frozenset
    Boolean Type: bool
    Binary Types: bytes, bytearray, memoryview
    Example Data Type
    x = "Hello World" str
    x = 20 int
    x = 20.5 float
    x = 1j complex
    x = ["apple", "banana", "cherry"] list
    x = ("apple", "banana", "cherry") tuple
    x = range(6) range
    x = {"name" : "John", "age" : 36} dict
    x = {"apple", "banana", "cherry"} set
    x = frozenset({"apple", "banana", "cherry"}) frozenset
    x = ==True== bool
    x = b"Hello" bytes
    x = bytearray(5) bytearray
    x = memoryview(bytes(5)) memoryview
    用e或者E来表示底数10
    x = 35e3
    y = 12E4
    z = -87.7e100
    
    随机数
    import random
    
    print(random.randrange(1, 10))#a number in [1,10)
    
    flont转int向下取整
    y = int(2.8) # y will be 2
    
    String常用的函数
    • strip()去掉字符串首尾空格
    • upper(), lower()大小写转换
    • replace()替换
    • split()分割字符串
    • 判断是否包含字串,innot in,类似Java中的contains()
    txt = "The rain in Spain stays mainly in the plain"
    x = "ain" in txt
    print(x)
    
    • +字符串拼接
    • 占位符使用
    quantity = 3
    itemno = 567
    price = 49.95
    myorder = "I want {} pieces of item {} for {} dollars."
    print(myorder.format(quantity, itemno, price))
    
    • 其他常用函数
    Method Description
    capitalize() Converts the first character to upper case
    casefold() Converts string into lower case
    center() Returns a centered string
    count() Returns the number of times a specified value occurs in a string
    encode() Returns an encoded version of the string
    endswith() Returns true if the string ends with the specified value
    expandtabs() Sets the tab size of the string
    find() Searches the string for a specified value and returns the position of where it was found
    format() Formats specified values in a string
    format_map() Formats specified values in a string
    index() Searches the string for a specified value and returns the position of where it was found
    isalnum() Returns True if all characters in the string are alphanumeric
    isalpha() Returns True if all characters in the string are in the alphabet
    isdecimal() Returns True if all characters in the string are decimals
    isdigit() Returns True if all characters in the string are digits
    isidentifier() Returns True if the string is an identifier
    islower() Returns True if all characters in the string are lower case
    isnumeric() Returns True if all characters in the string are numeric
    isprintable() Returns True if all characters in the string are printable
    isspace() Returns True if all characters in the string are whitespaces
    istitle() Returns True if the string follows the rules of a title
    isupper() Returns True if all characters in the string are upper case
    join() Joins the elements of an iterable to the end of the string
    ljust() Returns a left justified version of the string
    lower() Converts a string into lower case
    lstrip() Returns a left trim version of the string
    maketrans() Returns a translation table to be used in translations
    partition() Returns a tuple where the string is parted into three parts
    replace() Returns a string where a specified value is replaced with a specified value
    rfind() Searches the string for a specified value and returns the last position of where it was found
    rindex() Searches the string for a specified value and returns the last position of where it was found
    rjust() Returns a right justified version of the string
    rpartition() Returns a tuple where the string is parted into three parts
    rsplit() Splits the string at the specified separator, and returns a list
    rstrip() Returns a right trim version of the string
    split() Splits the string at the specified separator, and returns a list
    splitlines() Splits the string at line breaks and returns a list
    startswith() Returns true if the string starts with the specified value
    strip() Returns a trimmed version of the string
    swapcase() Swaps cases, lower case becomes upper case and vice versa
    title() Converts the first character of each word to upper case
    translate() Returns a translated string
    upper() Converts a string into upper case
    zfill() Fills the string with a specified number of 0 values at the beginning

    布尔值

    首字母大写
    True,False

    • 字符串
      不是空串为True,反之为False
    • 数字
      0:False,其他:True
    • 列表,元组,set,字典
      空集合:False,其他:True

    总结,下面的代码均会返回False

    bool(False)
    bool(None)
    bool(0)
    bool("")
    bool(())
    bool([])
    bool({})
    

    Python操作符
    ** 幂运算

    z = x ** y # z = x ^ y
    

    /浮点除法
    //结果向下取整

    浮点除和整数除

    Python不用&&,||!,而是

    python逻辑运算符

    其他语言没有的操作符
    in,not in

    x = ["apple", "banana"]
    print("banana" in x)
    # returns True because a sequence with the value "banana" is in the list
    

    Python数据结构

    • 列表([]来表示)
    thislist = ["apple", "banana", "cherry"]
    print(thislist)
    

    列表的增删改查

    thislist = ["apple", "banana", "cherry"]
    thislist.append("orange")
    thislist.insert(1, "orange")
    thislist.remove("banana")
    thislist.pop()
    del thislist[0]
    thislist.clear()
    del thislist
    #复制list
    mylist = thislist.copy()
    mylist1 = list(thislist)
    #合并list
    list1 = ["a", "b" , "c"]
    list2 = [1, 2, 3]
    list3 = list1 + list2
    print(list3)
    

    构造函数,注意((,))

    thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
    print(thislist)
    

    常用API


    list api
    • 元组( 用()来表示)
      unchangeable
    thistuple = ("apple", "banana", "cherry")
    print(len(thistuple))
    

    如果只要有一个元素,注意逗号

    thistuple = ("apple",)
    print(type(thistuple))#tuple
    
    thistuple = ("apple")
    print(type(thistuple))#str
    

    tuple()构造函数

    thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
    print(thistuple)
    
    • set
      unordered,unindexed,无序的,定义之后,无法确定它的顺序,所以不能通过下标的方式进行访问。
      set的增删改查
    thisset = {"apple", "banana", "cherry"}
    thisset.add("orange")#添加单个元素
    thisset.update(["orange", "mango", "grapes"])#添加过个元素
    #If the item to remove does not exist, discard() ,remove() will NOT raise an error.
    thisset.discard("banana")
    thisset.remove("banana")
    #两个set进行union
    set1 = {"a", "b" , "c"}
    set2 = {1, 2, 3}
    set3 = set1.union(set2)
    print(set3)
    

    使用update()合并

    set1 = {"a", "b" , "c"}
    set2 = {1, 2, 3}
    set1.update(set2)
    print(set1)
    

    set()构造函数

    thisset = set(("apple", "banana", "cherry")) # 注意是双括号
    print(thisset)
    
    • 字典Dictionary
    thisdict = {
      "brand": "Ford",
      "model": "Mustang",
      "year": 1964
    }
    print(thisdict)
    x = thisdict.get("model")
    thisdict["year"] = 2018
    #遍历key
    for x in thisdict:
      print(x)
    #遍历value
    for x in thisdict.values():
      print(x)
    #同时遍历key和value
    for x, y in thisdict.items():
      print(x, y)
    #删除
    del thisdict["model"]
    

    dict()构造函数

    thisdict = dict(brand="Ford", model="Mustang", year=1964)
    
    • if else语句
      elif
    a = 33
    b = 33
    if b > a:
      print("b is greater than a")
    elif a == b:
      print("a and b are equal")
    

    pass(什么都不做,作为占位符)

    a = 33
    b = 200
    
    if b > a:
      pass
    
    • 函数
      def
    def my_function():
      print("Hello from a function")
    
    my_function()
    

    变长参数的函数

    def my_function(*kids):
      print("The youngest child is " + kids[2])
    
    my_function("Emil", "Tobias", "Linus")
    

    带默认值的函数

    def my_function(country = "Norway"):
      print("I am from " + country)
    
    my_function("Sweden")
    my_function("India")
    my_function()
    my_function("Brazil")
    
    • Python Lambda
      lambda函数指的是一个小的匿名函数。
    #可以有多个参数,但是只能有一个语句
    lambda 参数: 语句
    # 语句会被执行,然后返回结果
    

    例如:

    x = lambda a, b : a * b
    print(x(5, 6))
    
    • 类和对象
    class MyClass:
      x = 5
    
    p1 = MyClass()
    print(p1.x)
    

    __init__()函数
    每个类都有__init__(),初始化函数,(类似Java的构造函数)

    class Person:
      def __init__(self, name, age):
    # self类似Java的this指针,指向当前对象。
        self.name = name
        self.age = age
    
    p1 = Person("John", 36)
    
    print(p1.name)
    print(p1.age)
    

    对象中添加方法:

    class Person:
      def __init__(self, name, age):
        self.name = name
        self.age = age
    
      def myfunc(self):
        print("Hello my name is " + self.name)
    
    p1 = Person("John", 36)
    p1.myfunc()
    
    • 继承
      父类:
    class Person:
      def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname
    
      def printname(self):
        print(self.firstname, self.lastname)
    

    子类:

    class Student(Person):
      pass
    

    调用父类的构造函数

    class Student(Person):
      def __init__(self, fname, lname):
        super().__init__(fname, lname)#super()
        self.graduationyear = 2019#子类添加graduationyear 域
    
      def welcome(self):#子类添加方法,同名可以override父类方法。
          print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
    
    
    • 迭代器
      python的列表、set和字典都是可以迭代的,iter()返回一个迭代器。
    mytuple = ("apple", "banana", "cherry")
    myit = iter(mytuple)
    
    print(next(myit))
    print(next(myit))
    print(next(myit)) 
    
    • Module模块
      module和库函数类似

    创建:

    #将代码保存为.py文件
    #mymodule.py
    def greeting(name):
      print("Hello, " + name)
    

    使用:

    import mymodule
    mymodule.greeting("Jonathan")
    

    重命名模块

    import mymodule as mx
    

    python自带

    相关文章

      网友评论

          本文标题:Python基础

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