Python基本语法

基础类型

python中的主要基本数据类型是数字(整数浮点数),布尔值字符串

字符串操作

  • 字符串可以被', ", '''包裹

  • 字符串是python的特殊类型。作为对象,在类中,可以使用.methodName()表示法调用字符串对象上的方法。字符串类在python中默认可用,因此不需要import语句即可将对象接口用于字符串。

    1
    2
    3
    firstVariable = 'Hello World'
    a = firstVariable.split(' ') # ['Hello', 'World']
    ' '.join(a) # 'Hello World'

  • 拼接字符串

    1
    2
    "0" * 3  # '000'
    "Fizz" + "Buzz" # 'FizzBuzz'

基础数学

  • 有四种不同的数字类型:普通整数,长整数,浮点数和复数。另外,布尔值是普通整数的子类型。
    1
    2
    3
    4
    5
    6
    7
    8
    # integer division
    130/2 # 65.0

    # Exponentiation
    2 ** 3 # 8

    # Modulo
    9 % 3 # 0

操作符

比较操作符 功能
< 小于
<= 小于或等于
> 大于
>= 大于或等于
== 等于
!= 不等于
逻辑操作符 描述
and 如果两个操作数均为True,则condition变为True.
or 如果两个操作数中的任何一个为True,则condition变为True.
not 用于反转逻辑(不是False变为True,而不是True变为False

列表

列表后面要加上方括号 [ ] - 切片

1
2
3
z = [3, 7, 4, 2]
z[0:2] #[3, 7]
z[:3] # [3, 7, 4]

  • 取列表的最大值, 最小值, 长度, 以及总和

    1
    print(min(z), max(z), len(z), sum(z)) # 2 7 4 16

  • 对列表中对象出现次数进行统计

    1
    2
    random_list = [4154104]
    random_list.count(4) # 3

  • 返回列表第一个指针

    1
    2
    3
    random_list.index(4) # 0
    random_list.index(4, 3) # 从索引3开始搜索第一个4的位置
    random_list.index(456) # random_list.index(value, [start, stop])

  • 对列表进行排序

    1
    2
    3
    4
    5
    6
    7
    8
    9
    x = [372118104]
    y = ['Steve''Rachel''Michael''Adam''Monica''Jessica''Lester']


    x.sort() # low to high
    x.sort(reverse = True) # high to low

    y.sort() # 按字典序排序
    new_list = sort(y) # 不改变原列表

  • 在列表结尾添加一个对象

    1
    x.append(3)

  • 删除列表中一个对象

    1
    x.remove(10)

  • 删除列表中指定位置的对象

    1
    2
    3
    4
    # Remove item at the index
    # this function will also return the item you removed from the list
    # Default is the last index
    x.pop(3)

  • 合并列表 通过在末尾续加的方式来延长列表

    1
    2
    x.extend([45])
    x + y # 列表里元素类型可以不同

  • 在列表指定位置前插入对象

    1
    x.insert(4, [45]) # [11, 10, 8, 4, [4, 5], 3, 2, 4, 5]

字典

字典是将键(key)映射到值(value)的无序数据结构。值可以是任何值(列表,函数,字符串,任何东西)。键(key)必须是不可变的,例如,数字,字符串或元组。 dict = {'key1': 'value1', 'key2': 'value2'} - 访问字典中的值

1
2
3
4
5
webstersDict ={'person': 'a human being, whether an adult or child',
'marathon': 'a running race that is about 26 miles',
'resist': ' to remain strong against the force or effect of (something)',
'run': 'to move with haste; act quickly'}
webstersDict['marathon']

  • 更新字典

    1
    2
    3
    4
    5
    6
    7
    8
    9
    # add one new key value pair to dictionary
    webstersDict['shoe'] = 'an external covering for the human foot'

    # update method, update or add more than key value pair at a time
    webstersDict.update({'shirt''a long- or short-sleeved garment for the upper part of the body''shoe''an external covering for the human foot, usually of leather and consisting of a more or less stiff or heavy sole and a lighter upper part ending a short distance above, at, or below the ankle.'})

    # Removing key from dictionary
    del webstersDict['resist']
    webstersDict

  • 不是所有东西都可以当作Key

  • 使用 get() 方法返回给定键的值

    1
    2
    3
    4
    storyCount = {'is'100'the'90'Michael'12'runs'5}
    storyCout['run'] # 报错
    storyCout.get('run') # None
    storyCout.get('run', 0) # 若不存在,则返回默认值0

  • 删除键,但同时可以返回值

    1
    count = storyCount.pop('the')

  • 遍历字典

    1
    2
    3
    4
    5
    # return keys in dictionary
    print(storyCount.keys())

    # return values in dictionary
    print(storyCount.values())

1
2
3
4
5
6
7
# iterate through keys
for key in storyCount: 
print(key)

# iterate through keys and values
for key, value in webstersDict.items():
print(key, value)

元组

元组是一种序列,就像列表一样。元组和列表之间的区别在于,与列表(可变)不同,元组不能更改(不可变)。 元组使用括号,而列表使用方括号。 - 初始化一个元组

1
2
3
4
5
6
7
8
9
10
11
emptyTuple = ()
emptyTuple = tuple()

# 可以通过用逗号分隔值的序列来初始化具有值的元组。
z = (3742)
z = 3742 # 也可以不要括号

# 要创建仅包含一个值的元组,则需要在项目后面添加一个逗号!
tup1 = ('Michael',)
tup2 = 'Michael',
notTuple = ('Michael') # This is a string, NOT a tuple.

  • 访问元组内的值

    1
    2
    z[0]
    z[-1] # 负索引

  • 切分元组

    1
    2
    3
    4
    5
    6
    7
    # Initialize a tuple
    z = (3742)

    # first index is inclusive (before the :) and last (after the :) is not.
    print(z[0:2])
    print(z[:3])
    print(z[-4:-1])

  • 元组是不可改变的,不过可以采用现有元组的一部分来创建新的元组

    1
    2
    3
    4
    5
    6
    7
    8
    9
    # Initialize tuple
    tup1 = ('Python''SQL')

    # Initialize another Tuple
    tup2 = ('R',)

    # Create new tuple based on existing tuples
    new_tuple = tup1 + tup2;
    print(new_tuple)

Tuple 方法

  • index 方法(索引)

    1
    2
    3
    4
    # Initialize a tuple
    animals = ('lama''sheep''lama'48)

    print(animals.index('lama'))

  • count 方法(计数)

    1
    print(animals.count('lama'))

  • 遍历元组

    1
    2
    for item in ('lama''sheep''lama'48):
        print(item)

  • 元组拆包

    1
    2
    3
    4
    # 元组对序列解包非常有用
    x, y = (710);
    print("Value of x is {}, the value of y is {}.".format(x, y))
    # Value of x is 7, the value of y is 10.

  • 枚举

    1
    2
    3
    4
    5
    # 枚举函数返回一个元组,其中包含每次迭代的计数(从默认为0的开始)和迭代序列获得的值
    friends = ('Steve''Rachel''Michael''Monica')
    for index, friend in enumerate(friends):

        print(index,friend)

元组相对列表的优势

  • 元组比列表更快。如果要定义一组常量值,迭代它,使用元组而不是列表。

  • 元组可以作为字典键,列表不可以用作字典键

    1
    2
    3
    4
    5
    bigramsTupleDict = {('this''is'): 23,
                        ('is''a'): 12,
                        ('a''sentence'): 2}

    print(bigramsTupleDict)

  • 元组可以是集合中的值,列表不可以是集合中的值

    1
    2
    3
    4
    5
    graphicDesigner = {('this''is'),
                       ('is''a'),
                       ('a''sentence')}

    print(graphicDesigner)
    ### 生成斐波那契序列
    1
    2
    3
    4
    5
    # 打印出前10个Fibonacci数
    a,b = 1,1
    for i in range(10):
        print("Fib(a): ", a, "b is: ", b)
        a,b = b,a+b

for 循环

Task: 从文本中删除标点符号并将最终产品转换为列表:

1
2
3
4
5
6
7
8
9
10
11
12
text = '''On a dark desert highway, cool wind in my hair Warm smell of colitas, rising up through the air Up ahead in the distance, I saw a shimmering light My head grew heavy and my sight grew dim I had to stop for the night There she stood in the doorway; I heard the mission bell And I was thinking to myself, "This could be Heaven or this could be Hell" Then she lit up a candle and she showed me the way'''

for char in '-.,;\n"\'':
text = text.replance(char, ' ')
# Split converts string to list.
text.split(' ')[0:20] # 取前20个

cleaned_list = []
for word in text.split(' '): 
    word_length = len(word)
    if word_length > 0:
        cleaned_list.append(word)
### range 函数
1
2
3
4
5
6
7
8
9
# Making empty lists to append even and odd numbers to. 
even_numbers = []
odd_numbers = []

for number in range(1,51):
    if number % 2 == 0:
        even_numbers.append(number)
    else
        odd_numbers.append(number)
## 函数 ### 创建函数的语法
1
2
3
def function_name(parameters): 
"""docstring"""
statement(s)
上面显示的是一个函数定义,它由以下组件组成。 1. 关键字def标记函数头的开始。 2. 用于唯一标识它的函数名称。函数命名遵循在Python中编写标识符的相同规则。 3. 参数(参数),我们通过它将值传递给函数。它们是可选的。 4. 冒号(:)标记函数头的结尾。 5. 用于描述函数功能的可选文档字符串(docstring)。 6. 构成函数体的一个或多个有效的python语句。语句必须具有相同的缩进级别(通常为4个空格)。 7. 用于从函数返回值的可选return语句。

返回语句

return语句用于退出函数并返回到调用函数的位置。

1
return [expression_list]
此语句可以包含要求求值的表达式,并返回值。如果语句中没有表达式,或者函数内部不存在return语句本身,则该函数将返回None对象。 ### 变量函数参数 - 默认参数 但是一旦我们有一个默认参数,它右边的所有参数也必须有默认值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
def greet(name, msg = "Good morning!"):
   """
   This function greets to
   the person with the
   provided message.

   If message is not provided,
   it defaults to "Good
   morning!"
   """
   print("Hello",name + ', ' + msg)

greet("Kate")
greet("Bruce","How do you do?")

  • 关键字参数 在函数调用期间将位置参数与关键字参数混合使用。但必须记住,关键字参数必须遵循位置参数。在关键字参数之后使用位置参数将导致错误。

    1
    2
    # greet(msg = "How do you do?", "Bruce")
    greet("Bruce",msg = "How do you do?")

  • 任意参数 事先并不知道将传递给函数的参数数量。Python允许我们通过具有任意数量参数的函数调用来处理这种情况。这些参数在传递给函数之前被包装到元组中。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    def greet(*names):
       """This function greets all
       the person in the names tuple."""

       # names is a tuple with arguments
       for name in names:
           print("Hello",name)

    greet("Monica","Luke","Steve","John")
    ### 在列表中移除重复元素
    1
    2
    3
    4
    5
    6
    7
    8
    9
    def remove_duplicates(duplicate): 
        uniques = [] 
        for num in duplicate: 
            if num not in uniques: 
                uniques.append(num) 
        return(uniques)

    duplicate = [24102052204
    print(remove_duplicates(duplicate))

Python面向对象编程

面向对象编程(Object-oriented Programming,简称OOP)是一种编程范例,它提供了一种结构化程序的方法,以便将属性和行为捆绑到单个对象中。 ### Python中的类 一个类只提供结构 - 它是应该如何定义某个东西的蓝图,但它实际上并不提供任何真实的内容。可以将"类"视为"某事物的定义",每个事物或对象都是某个类的实例。 ### Python对象(实例) 在创建对象的单个实例之前,我们必须首先通过定义类来指定所需的内容。 ### 定义和使用方法

1
2
class Dog: 
pass
使用class关键字指示正在创建一个类,然后添加该类的名称(使用骆驼命名法,以大写字母开头。)

实例属性

所有类都需要创建对象,所有对象都包含称为属性的特征。使用__init __方法通过为对象的初始属性提供其默认值(或状态)来初始化(例如,指定)对象的初始属性。此方法必须至少有一个参数以及自变量,它引用对象本身(例如,Dog)。

1
2
3
4
5
class Dog: 
# Initializer / Instance Attributes
def __init__(self, name, age):
self.name = name
self.age = age

创建一个新的实例时__init__会被自动调用。

类属性

1
2
3
4
5
6
7
8
class Dog: 
# Class Attribute
species = 'mammal'

# Initializer / Instance Attributes
def __init__(self, name, age):
self.name = name
self.age = age

实例化对象

1
2
3
4
5
6
7
8
9
10
11
12
>>> Dog() 
>>> <__main__.Dog object at 0x1004ccc50>
>>> Dog()
>>> <__main__.Dog object at 0x1004ccc90>

>>> a = Dog()
>>> b = Dog()
>>> a == b
False

>>> type(a)
<class '__main__.Dog'>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Dog:
    # Class Attribute
    species = 'mammal'
    # Initializer / Instance Attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Instantiate the Dog object
philo = Dog("Philo"5)
mikey = Dog("Mikey"6)

# Access the instance attributes
# 使用点表示法来访问每个对象的属性
print("{} is {} and {} is {}.".format(
philo.name, philo.age, mikey.name, mikey.age))

# Is Philo a mammal?
if philo.species == "mammal":
    print("{0} is a {1}!".format(philo.name, philo.species))

实例方法

实例方法在类中定义,用于获取实例的内容。 它们还可用于使用对象的属性执行操作。与__init__方法一样,第一个参数始终是self

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Dog:
    # Class Attribute
    species = 'mammal'

    # Initializer / Instance Attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    # instance method
    def description(self):
        return "{} is {} years old".format(self.name, self.age)

    # instance method
    def speak(self, sound):
        return "{} says {}".format(self.name, sound)

# Instantiate the Dog object
mikey = Dog("Mikey"6)

# call our instance methods
print(mikey.description())
print(mikey.speak("Gruff Gruff"))

  • 修改属性
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class Email: 
    def __init__(self):
    self.is_sent = False
    def send_email(self):
    self.is_sent = True

    my_email = Email()
    print(my_email.is_sent)

    my_email.send_email()
    print(my_email.is_sent)

Python对象继承

继承是一个类采用另一个类的属性和方法的过程。新形成的类称为子类,子类派生的类称为父类。 重要的是要注意子类覆盖扩展父类的功能(例如,属性和行为)。换句话说,子类继承了父项的所有属性和行为,但也可以添加不同行为。最基本的类是一个对象,通常所有其他类都继承为它们的父对象。 定义新类时,Python 3隐式使用object作为父类。所以以下两个定义是等价的:

1
2
3
4
5
6
class Dog(object): 
pass

# In Python 3, this is the same as:
class Dog:
pass

  • 扩展父类功能

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    # Child class (inherits from Dog class)
    class RussellTerrier(Dog):
        def run(self, speed):
            return "{} runs {}".format(self.name, speed)

    # Child class (inherits from Dog class)
    class Bulldog(Dog):
        def run(self, speed):
            return "{} runs {}".format(self.name, speed)

    # Child classes inherit attributes and
    # behaviors from the parent class
    jim = Bulldog("Jim"12)
    print(jim.description()) # Jim is 12 years old

    # Child classes have specific attributes
    # and behaviors as well
    print(jim.run("slowly")) # Jim runs slowly

  • 覆盖父类功能 isinstance()函数用于确定实例是否也是某个父类的实例。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    class Dog: 
    species = 'mammal'
    class SomeBreed(Dog):
    pass
    class SomeOtherBreed(Dog):
    species = 'reptile'

    frank = SomeBreed()
    print(frank.species) # mammal

    beans = SomeOtherBreed()
    print(beans.species) # reptile


Python基本语法
https://nessaj7.github.io/2021/11/16/7bf8ece318c3.html
作者
kuhn
发布于
2021年11月16日
许可协议