Python基础语法

目录

Python基础语法

博主对Python基础语法作了总结归纳。

数据类型

示例代码:

age = age1 = age2 = 18
name = "york sun"
name2 = 'york sun 2' # '' and "" can be ok
print(name, age, "\n")

age3, age4, age5 = 13, 14, 15
print(age1, age2, age3, age4, age5)

age6 = age5
print(id(age5)) # id():memory address of variables
print(id(age6))
print(bool(age5 is age6), "\n")

msg1 = 'What\'s your name?'
print(msg1, "\n")

a, b = 10, 3
print(a + b, a - b, a * b, a / b, a // b, a % b, a ** b, "\n")

print(bool(0), bool(1), bool(2), True, not True)
print(type(age), type(True), type(None), "\n")

name3 = input("Please input your name: ")
print("Your name is: " + name3) # no separation
print("Your name is: ", name3) # separated with a blank
age7 = input("Please input your age: ")
if age7.isdigit():
    print("Your age is: " + age7, "\n")
else:
    print("Wrong age", "\n")

运行结果:

york sun 18

18 18 13 14 15

1581123044016

1581123044016

True

What’s your name?

13 7 30 3.3333333333333335 3 1 1000

False True True True False

<class ‘int’> <class ‘bool’> <class ‘NoneType’>

Please input your name: york sun

Your name is: york sun

Your name is: york sun

Please input your age: 19

Your age is: 19

数据结构

list 示例代码:

# list
phones1 = list()
phones1.append("Apple")
phones1.append("Samsung")
phones1.append("Huawei")
print("phones1:", phones1)
phones2 = ["Apple", "Huawei", "Samsung", "Huawei"]
print("phones2:", phones2)
# add delete change search
print(phones1[0], phones1.index("Apple"), phones2.count("Huawei"), len(phones1))
phones1.append("OPPO")
phones1.insert(1, "vivo")
phones1.extend(phones2)
print("phones1 after appending, inserting, extending:", phones1)
phones1.pop()
print("phones1 pop():", phones1)
phones1.remove("Apple")
print("phones1 remove Apple:", phones1)
phones2.clear()
print("phones2 clear:", phones2)
del phones1[1]
print("phones1 del:", phones1)
del phones1[1:3]  # delete elements whose indexes are in [1:3)
print("phones1 del:", phones1)
# reverse
phones1.reverse()
print("phones1 reverse:", phones1)
# sort
list1 = [3, 2, 5, 1, 6, 4]
print("list1:", list1)
print("list1.sort():", list1.sort())
print("list1:", list1)
list2 = [3, 2, 5, 1, 6, 4]
print("list2:", list2)
print("sorted(list2):", sorted(list2))
print("list2:", list2, "\n")

运行结果:

phones1: [‘Apple’, ‘Samsung’, ‘Huawei’]

phones2: [‘Apple’, ‘Huawei’, ‘Samsung’, ‘Huawei’]

Apple 0 2 3

phones1 after appending, inserting, extending: [‘Apple’, ‘vivo’, ‘Samsung’, ‘Huawei’, ‘OPPO’, ‘Apple’, ‘Huawei’, ‘Samsung’, ‘Huawei’]

phones1 pop(): [‘Apple’, ‘vivo’, ‘Samsung’, ‘Huawei’, ‘OPPO’, ‘Apple’, ‘Huawei’, ‘Samsung’]

phones1 remove Apple: [‘vivo’, ‘Samsung’, ‘Huawei’, ‘OPPO’, ‘Apple’, ‘Huawei’, ‘Samsung’]

phones2 clear: []

phones1 del: [‘vivo’, ‘Huawei’, ‘OPPO’, ‘Apple’, ‘Huawei’, ‘Samsung’]

phones1 del: [‘vivo’, ‘Apple’, ‘Huawei’, ‘Samsung’]

phones1 reverse: [‘Samsung’, ‘Huawei’, ‘Apple’, ‘vivo’]

list1: [3, 2, 5, 1, 6, 4]

list1.sort(): None

list1: [1, 2, 3, 4, 5, 6]

list2: [3, 2, 5, 1, 6, 4]

sorted(list2): [1, 2, 3, 4, 5, 6]

list2: [3, 2, 5, 1, 6, 4]

tuple 示例代码:

# tuple
tuple1 = (1, 2, 3, 4)  # tuple cannot be changed
tuple2 = 1, 2, 3, 4
tuple3 = 1,  # tuple with one element
tuple4 = ()  # tuple without element
print("tuple1 to tuple4:", tuple1, tuple2, tuple3, tuple4, )
# tuple cannot be changed
print("tuple1[0]:", tuple1[0])
# tuple and list transfer
print("type(tuple1):", type(tuple1))
list(tuple1)
print(type(tuple1))
print(type(list(tuple1)))
list3 = [1, 2, 3, 4, 5]
print(type(list3))
tuple(list3)
print(type(list3))
print(type(tuple(list3)))

运行结果:

tuple1 to tuple4: (1, 2, 3, 4) (1, 2, 3, 4) (1,) ()

tuple1[0]: 1

type(tuple1): <class ‘tuple’>

<class ‘tuple’>

<class ‘list’>

<class ‘list’>

<class ‘list’>

<class ‘tuple’>

dict 示例代码:

# dict
dict1 = dict(name="york sun", age=18)
print(dict1)
dict2 = {"name": "york sun", "age": 18}
print(dict2)
info = [('name', 'york sun'), ('age', 18)]
print(dict(info))  # pay attention to () [] and {}
# add delete change search
print(dict1["name"])  # no index in dict, put a key in the []
# print(dict1[2]) Error
print(dict1.get("age", 20))
print(dict1.get("gender", "male"))  # output default value
dict1["gender"] = "male"
print(dict1)
dict1["age"] = 19
print("dict1 delete age:", dict1)
dict3 = dict(name="york sun", age=18)
dict3.pop("age")  # parameter of pop cannot be null
print("dict3 delete age:", dict3)
dict4 = dict(name="york sun", age=18)
del dict4["age"]
print("dict4 delete age:", dict4)

运行结果:

{‘name’: ‘york sun’, ‘age’: 18}

{‘name’: ‘york sun’, ‘age’: 18}

{‘name’: ‘york sun’, ‘age’: 18}

york sun

18

male

{‘name’: ‘york sun’, ‘age’: 18, ‘gender’: ‘male’}

dict1 delete age: {‘name’: ‘york sun’, ‘age’: 19, ‘gender’: ‘male’}

dict3 delete age: {‘name’: ‘york sun’}

dict4 delete age: {‘name’: ‘york sun’}

set 示例代码:

# set
set1 = {"Apple", "Huawei", "Xiaomi"}
print("set1: ", set1)
set2 = set(["Apple", "Huawei", "Xiaomi"])
print("set2: ", set2)
# add delete change search
set3 = set()
set3.add("Apple")
set3.add("Huawei")
print("set3: ", set3)
set4 = set()
set4.update({"Apple"})
set4.update(["Huawei"])
set4.update(("Xiaomi",))  # cannot be without the ','
set4.update({"OPPO": "123"})
print("set4: ", set4)
set4.remove("OPPO")  # Error if no parameter in function remove()
print("set4: ", set4)
set4.discard("vivo")  # Error if no parameter in function discard()
print("set4: ", set4)
set4.pop()  # delete an element randomly
print("set4: ", set4)
set4.clear()
print("set4: ", set4)
# compute
set5 = {"Apple", "Huawei"}
set6 = {"Xiaomi", "Huawei"}
print("set5: ", set5, "\n" + "set6: ", set6)
print("set5.union(set6): ", set5.union(set6))
print("set5 | set6: ", set5 | set6)
print("set5.difference(set6): ", set5.difference(set6))
print("set5 - set6: ", set5 - set6)
print("set5.intersection(set6): ", set5.intersection(set6))
print("set5.symmetric_difference(set6)", set5.symmetric_difference(set6))

运行结果:

set1: {‘Apple’, ‘Xiaomi’, ‘Huawei’}

set2: {‘Xiaomi’, ‘Huawei’, ‘Apple’}

set3: {‘Huawei’, ‘Apple’}

set4: {‘Xiaomi’, ‘Huawei’, ‘Apple’, ‘OPPO’}

set4: {‘Xiaomi’, ‘Huawei’, ‘Apple’}

set4: {‘Xiaomi’, ‘Huawei’, ‘Apple’}

set4: {‘Huawei’, ‘Apple’}

set4: set()

set5: {‘Huawei’, ‘Apple’}

set6: {‘Xiaomi’, ‘Huawei’}

set5.union(set6): {‘Xiaomi’, ‘Huawei’, ‘Apple’}

set5 set6: {‘Xiaomi’, ‘Huawei’, ‘Apple’}

set5.difference(set6): {‘Apple’}

set5 - set6: {‘Apple’}

set5.intersection(set6): {‘Huawei’}

set5.symmetric_difference(set6) {‘Xiaomi’, ‘Apple’}

iterator 示例代码:

# iterator
set1 = {"Apple", "Huawei", "Xiaomi"} # list, tuple, dict, set and strings can be iterated
for i in set1:
    print(i)
list1 = [0, 1, 2, 3]
gen = iter(list1)
for i in range(5):
    if i == 0:
        print(gen)
    else:
        print(next(gen))
gen = iter(list1)
for _ in range(4):
    print(next(gen))

运行结果:

Apple

Xiaomi

Huawei

<list_iterator object at 0x000001D60D7EFF40>

0

1

2

3

0

1

2

3

generator 示例代码:

# generator
gen1 = (i for i in range(5))
print("gen1:", gen1)
def generator_factory(top = 5):
     index = 0
     while index < top:
         print("index value:" + str(index))
         index = index + 1
         yield index
     raise StopIteration

gen = generator_factory()
gen.send(None)
gen.send(None)
gen.send(None)
gen.send(None)
gen.send(None)

运行结果:

gen1: <generator object at 0x000001D60D779A80>

index value:0

index value:1

index value:2

index value:3

index value:4

控制流程

if 示例代码:

# if
age = 20
if age >= 18: # pay attention to ':'
    print("adult")
else:
    print("nonage")

score = 75
if score >= 90:
    print("excellent")
elif score >= 80:
    print("great")
elif score >= 70:
    print("good")
elif score >= 60:
    print("qualified")
else:
    print("unqualified")

if age >=18 and score >= 60:
    print("adult and qualified")
if age <40 or score >= 60:
    print("not middle-aged or qualified")
if not age >= 40:
    print("not middle-aged", "\n")

运行结果:

adult

good

adult and qualified

not middle-aged or qualified

not middle-aged

for 示例代码:

# for
phones = ["Apple", "Huawei", "Xiaomi"]
for phone in phones:
    print("current phone:", phone)
for index, phone in enumerate(phones):
    print("my phone{} is {}".format(index + 1, phone))
for i in [0, 1, 2]:
    if i ==1:
        print(f"current number is {i}, gonna quit circulation")
        break
    print(f"current number is {i}")
for i in [0, 1, 2]:
    if i == 1:
        continue
    print(f"current number is {i}")
for i in [0, 1, 2]:
    if i == 1:
        print(f"current number is {i}")
        break
else:
    print("circulation is normal") # for-else: do not execute else statement after break, otherwise execute statement
for i in range(4):
    print(f"print 4 times. this is time {i}")
for _ in range(3):
    print(f"print 3 times")
for index, item in enumerate(["Apple", "Huawei", "Xiaomi"]):
    print(f"phone {index} is {item}")

运行结果:

current phone: Apple

current phone: Huawei

current phone: Xiaomi

my phone1 is Apple

my phone2 is Huawei

my phone3 is Xiaomi

current number is 0

current number is 1, gonna quit circulation

current number is 0

current number is 2

current number is 1

print 4 times. this is time 0

print 4 times. this is time 1

print 4 times. this is time 2

print 4 times. this is time 3

print 3 times

print 3 times

print 3 times

phone 0 is Apple

phone 1 is Huawei

phone 2 is Xiaomi

while 示例代码:

# while
age = 1
while age <= 3:
    print(f"child is {age}-year-old. cannot go to nursery")
    age += 1
print("can go to nursery")

运行结果:

child is 1-year-old. cannot go to nursery

child is 2-year-old. cannot go to nursery

child is 3-year-old. cannot go to nursery

can go to nursery

comprehension 示例代码:

# comprehensions
# list comprehension
old_list = [0, 1, 2, 3, 4, 5]
print("old_list:", old_list)
new_list = [item1 for item1 in old_list if item1 % 2 == 0]
print("new_list:", new_list)
# dict comprehension
old_info = {"Jack": {"Chinese": 87, "math": 92, "English": 78},
            "Tom": {"Chinese": 92, "math": 100, "English":89}}
print("old_info:", old_info)
new_info = {name: scores for name, scores in old_info.items() if scores["math"] == 100}
print("new_info:", new_info)
old_info1 = {"name": "york sun", "age": 18, "gender": "male"}
print("old_info1:", old_info1)
new_info1 = {key_: val_ for key_, val_ in old_info1.items() if val_ == 18}
print("new_info1:", new_info1)
# set comprehension
old_list1 = [0, 0, 0, 1, 2, 3]
print("old_list1:", old_list1)
new_list1 = {item for item in old_list1}
print("new_list1:", new_list1)

运行结果:

old_list: [0, 1, 2, 3, 4, 5]

new_list: [0, 2, 4]

old_info: {‘Jack’: {‘Chinese’: 87, ‘math’: 92, ‘English’: 78}, ‘Tom’: {‘Chinese’: 92, ‘math’: 100, ‘English’: 89}}

new_info: {‘Tom’: {‘Chinese’: 92, ‘math’: 100, ‘English’: 89}}

old_info1: {‘name’: ‘york sun’, ‘age’: 18, ‘gender’: ‘male’}

new_info1: {‘age’: 18}

old_list1: [0, 0, 0, 1, 2, 3]

new_list1: {0, 1, 2, 3}

学习函数

function create and invoke 示例代码:

# function create and invoke
print("---function create and invoke---")
def get_average(a, b):
    result = (a + b) / 2
    return result
average = get_average(2, 6)
print("average:", average)

def fact(n):
    if(n == 1):
        return 1
    return fact(n - 1) * n
fact1 = fact(5)
print("fact1:", fact1)

运行结果:

—function create and invoke—

average: 4.0

fact1: 120

parameter of function 示例代码:

# parameter of function
print("---parameter of function---")
def func1(a, b, c = 0, d = 1): # a, b are required. c, d are optional with default values 0 and 1
    # required parameters must precede optional parameters
    pass
func1(10, 20, 30, 40)
def func2(*args, **kw): # *args must precede **kw
    print("args:", args) # *arg: tuple type
    print("kw:", kw) # **kw: dict type
func2(10, 11, c = 20, d = 21)
# *args can precede required parameters
def func3(*args, b):
    print("args:", args)
    print("b:", b)
func3(1, 2, b = 100)
# func3(1, b = 100, 2) Error
# func3(b = 100, 1, 2) Error
# **kw must be put at last position:
# def func4(**kw, a): Error
# def func4(**kw, a = 1): Error
# def func4(**kw, *arg): Error
def func5(a, b, *, c):
    print("a, b, c:", a, b, c)
# func5(1, 2, 3) Error
func5(1, 2, c = 3)
# passing parameters pass the memory addressed of parameters
def func6(item_, list_):
    list_.append(item_)
list1 = [0, 1]
print("list1:", list1)
func6(2, list1)
print("list1:", list1)

运行结果:

—parameter of function—

args: (10, 11)

kw: {‘c’: 20, ‘d’: 21}

args: (1, 2)

b: 100

a, b, c: 1 2 3

list1: [0, 1]

list1: [0, 1, 2]

lambda 示例代码:

# lambda
print("---lambda---")
print("(lambda x, y: x + y)(2, 4):", (lambda x, y: x + y)(2, 3))
print("(lambda x: (lambda y: (lambda z: x + y + z)(3))(2))(1):", (lambda x: (lambda y: (lambda z: x + y + z)(3))(2))(1))
func7 = lambda n: 1 if n == 0 else n * func7(n - 1)
print("func7(5):", func7(5))
func8 = lambda func_, n: 1 if n == 0 else n * func_(func_, n - 1)
print("func8(func8, 5):", func8(func8, 5))

运行结果:

—lambda—

(lambda x, y: x + y)(2, 4): 5

(lambda x: (lambda y: (lambda z: x + y + z)(3))(2))(1): 6

func7(5): 120

func8(func8, 5): 120

advanced function 示例代码:

# advanced function
print("---advanced function---")
print("map(lambda x: x * 2, [1, 2, 3, 4, 5]):", map(lambda x: x * 2, [1, 2, 3, 4, 5]))
print("list(map(lambda x: x * 2, [1, 2, 3, 4, 5])):", list(map(lambda x: x * 2, [1, 2, 3, 4, 5])))
print("filter(lambda x: x < 0, range(-5, 5)):", filter(lambda x: x < 0, range(-5, 5)))
print("list(filter(lambda x: x < 0, range(-5, 5))):", list(filter(lambda x: x < 0, range(-5, 5))))
print("reduce(lambda x, y: x + y, [1, 2, 3, 4, 5]):", reduce(lambda x, y: x + y, [1, 2, 3, 4, 5]))

运行结果:

—advanced function—

map(lambda x: x * 2, [1, 2, 3, 4, 5]): <map object at 0x0000026EB1FB74C0>

list(map(lambda x: x * 2, [1, 2, 3, 4, 5])): [2, 4, 6, 8, 10]

filter(lambda x: x < 0, range(-5, 5)): <filter object at 0x0000026EB1FB74C0>

list(filter(lambda x: x < 0, range(-5, 5))): [-5, -4, -3, -2, -1]

reduce(lambda x, y: x + y, [1, 2, 3, 4, 5]): 15

reflection function 示例代码:

# reflection function
print("---reflection function---")
print("type(1):", type(1)) # return type of object
print("type([]):", type([]))
print("dir(json):", dir(json)) # return attribute list
print("hasattr(json, 'dumps'):", hasattr(json, "dumps"))
print("getattr(json, 'dumps'):", getattr(json, "dumps"))
a = 5
print("id(a):", id(a)) # return unique identifier of an object(int)
print("isinstance(10, int):", isinstance(10, int)) # return whether an object is an instance of a class
# print(json.__doc__) search doc of a module
import json as js
print("js.__name__:", js.__name__) # module name when defined
print("js.__file__:", js.__file__) # file path

运行结果:

—reflection function—

type(1): <class ‘int’>

type([]): <class ‘list’>

dir(json): [‘JSONDecodeError’, ‘JSONDecoder’, ‘JSONEncoder’, ‘__all__’, ‘__author__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__path__’, ‘__spec__’, ‘__version__’, ‘_default_decoder’, ‘_default_encoder’, ‘codecs’, ‘decoder’, ‘detect_encoding’, ‘dump’, ‘dumps’, ‘encoder’, ‘load’, ‘loads’, ‘scanner’]

hasattr(json, ‘dumps’): True

getattr(json, ‘dumps’): <function dumps at 0x0000026EB1FB81F0>

id(a): 2674450760048

isinstance(10, int): True

js.__name__: json

js.__file__: C:\Python310\lib\json__init__.py

scope of variable 示例代码:

# scope of variable
print("---scope of variable---")
# closure
def deco():
    name = "MING"
    def wrapper():
        print("name is:", name)
    return wrapper()
deco()
# change scope
# global() changes local variable to global variable; nonlocal() allows to use variables-out-closure in a closure
def deco1():
    age = 10
    def wrapper():
        nonlocal age # Error if without this line
        age += 1
        print("age:", age)
    return wrapper()
deco1()
# variable set
# globals() store all global variables as dict
def foo():
    print("run foo()")
def bar():
    foo_dup = globals().get("foo")
    foo_dup()
bar()
# locals() store all global variables as dict
def foobar():
    name = "MING"
    gender = "male"
    for key, value in locals().items():
        print(key, "=", gender)
foobar()

运行结果:

—scope of variable—

name is: MING

age: 11

run foo()

name = male

gender = male

类与对象

class 示例代码:

# class
print("---class---")
class Animal1:
    def __init__(self, name):
        self.name = name
    def run(self):
        print(f"{self.name} runs")
dog1 = Animal1(name="dog1")
print("dog1.name:", dog1.name)
dog1.run()
Animal1.run(dog1)

运行结果:

—class—

dog1.name: dog1

dog1 runs

dog1 runs

static method and class method 示例代码:

# static method and class method
class Animal2:
    def __init__(self, name):
        self.name = name
    # ordinary instance method, the first parameter is self
    def run(self):
        print(f"{self.name} runs")
    # static method, need not parameter self
    @staticmethod
    def eat():
        print("eats")
    # class method, the first method is cls, need not parameter cls when invoked
    @classmethod
    def jump(cls, name):
        print(f"{name} jumps")
dog2 = Animal2(name="dog2")
dog2.run()
dog2.eat()
dog2.jump("dog2")
Animal2.jump("dog2")
Animal2.jump("dog3")
# difference between method and function
def demo_func():
    pass
print("ordinary function demo_func() and static method eat():", type(demo_func), type(dog2.eat))
print("instance method run() and class method jump():", type(dog2.run), type(dog2.jump))
print("method is a special function, which is because method is bound with object(instance or class)")

运行结果:

dog2 runs

eats

dog2 jumps

dog2 jumps

dog3 jumps

ordinary function demo_func() and static method eat(): <class ‘function’> <class ‘function’>

instance method run() and class method jump(): <class ‘method’> <class ‘method’>

method is a special function, which is because method is bound with object(instance or class)

private variable and private method 示例代码:

# private variable and private method
print("---private variable and private method---")
"""
5 meanings of Python underline:
single leading underline: _var
double leading underline: __var
single end underline: var_
double leading and end underline: __var__
single underline: _
"""
# single leading underline: _var
# variable or method leading with single underline use only inside
class Demo1:
    def __init__(self):
        self.foo = 11
        self._bar = 22
        self.__baz = 33
demo1 = Demo1()
print("demo1.foo:", demo1.foo)
# print("demo1._bar:", demo1._bar) not Error, but not recommend
# double leading underline:__var
# demo1.__baz Error, variables with double leading underline are private, and connot be invoked directly by instance object or class
print("demo1._Demo1__baz:", demo1._Demo1__baz) # can only be invoked through instance._classname__methodname
# single end underline: var_
# avoid conflicting with Python keywords
# def make_object(name, class) Error, class is keyword
def make_object(name, class_):
    pass
# double leading and end underline: __var__
# Python define special method. avoid using in your own program
# single underline: _
# showing a variable is temporary or unimportant
for _ in range(3):
    print("Hello, world")

运行结果:

—private variable and private method—

demo1.foo: 11

demo1._Demo1__baz: 33

Hello, world

Hello, world

Hello, world

商业转载请联系博主获得授权,非商业转载请注明出处!

分享结束,大家辛苦了。散会!

-->