python基础语法2

python基础语法2

了解整体内容可以从基础语法1开始,第2天了,开始上代码片段。

本篇主要内容:控制流语句if、for、match等。


  1. 打印及main方法
python 复制代码
# 注释使用#号
#打印hello
def print_hello(name):
    #这里加上f是打印变量内容,不加f打印的是{name}
    print(f'hello, {name}')

# 启动方法,要写到函数方法的下面
if __name__ == '__main__':
    print_hello('PyCharm')
    
打印效果:hello, PyCharm
  1. if语句
python 复制代码
def if_statement():
    x=1
    if x<1:
        print('x<1')
    elif x==1:
        print('x==1')
    else:
        print('x>1')

打印效果:x==1
  1. for循环
python 复制代码
def for_statement():
	#列表循环输出
    fruits=["apple","banana",'watermelon']
    for item in fruits:
        print(item,len(item),'水果')
	
	#集合循环控制
    fruitsKeyValue = {"apple":"red", "banana":'yellow', 'watermelon':'green'}
    #尝试修改fruits里的内容,可以copy副本
    for fruit, status in fruitsKeyValue.copy().items():
        if status == 'green':
            #删除西瓜
            del fruitsKeyValue[fruit]

    print(fruitsKeyValue)
    #再加回西瓜
    fruitsKeyValue.update({'watermelon':'green'})
    print(fruitsKeyValue)

    #尝试修改fruits里的内容,创新的集合
    active_fruits = {}
    for fruit, status in fruitsKeyValue.items():
        if status == 'yellow':
            active_fruits[fruit] = status
    print(active_fruits)

打印效果:
apple 5 水果
banana 6 水果
watermelon 10 水果
{'apple': 'red', 'banana': 'yellow'}
{'apple': 'red', 'banana': 'yellow', 'watermelon': 'green'}
{'banana': 'yellow'}
  1. range函数,range迭代效果类似list,实际存储并不是列表,所以节省空间。
python 复制代码
def range_function():
    #从0--5
    for i in range(5):
        print(i)
    #5--10,步长1
    print(list(range(5, 10)))
    #0--10,步长3
    print(list(range(0, 10, 3)))

打印效果:
0
1
2
3
4
[5, 6, 7, 8, 9]
[0, 3, 6, 9]
  1. break、continue、else子句
    break 语句将跳出最近的一层 for 或 while 循环;
    continue 语句,跳出本次循环,进入下一循环;
    在 for 循环中,else 子句会在循环成功结束最后一次迭代之后执行;
    在 while 循环中,else 子句会在循环条件变为假值后执行;
    无论哪种循环,如果因为 break 而结束,那么 else 子句就不会执行。
python 复制代码
def loop_function():
    for n in range(2, 10):
        for x in range(2, n):
            if n % x == 0:
                print(n, 'equals', x, '*', n // x)
                break
        else:
            print(n, '是质数')

    for num in range(2, 10):
        if num % 2 == 0:
            print("偶数", num)
            continue
        print("奇数", num)

打印效果:
2 是质数
3 是质数
4 equals 2 * 2
5 是质数
6 equals 2 * 3
7 是质数
8 equals 2 * 4
9 equals 3 * 3
偶数 2
奇数 3
偶数 4
奇数 5
偶数 6
奇数 7
偶数 8
奇数 9
  1. pass语句
    pass 语句不执行任何动作,可占位。
python 复制代码
while True:
    pass
def initlog():
    pass
  1. match语句
    一个主语值与多个字面比较的例子:
python 复制代码
def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        #组合型,|和or都可以
        case 401 | 403 | 404:
            return "Not allowed"
        #_是通配符,必定会匹配成功
        case _:
            return "Something's wrong with the internet"

打印效果:Something's wrong with the internet

也可以类似于解包赋值的方式:

python 复制代码
def match_point():
    point=(5,5)
    match point:
        case (0, 0):
            print("Origin")
        case (0, y):
            print(f"Y={y}")
        case (x, 0):
            print(f"X={x}")
        case (x, y):
            print(f"X={x}, Y={y}")
        case _:
            raise ValueError("Not a point")
          
打印效果:X=5, Y=5

类组织数据的方式:

python 复制代码
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def where_is():
    point = Point(x=0, y=0)
    match point:
        case Point(x=0, y=0):
            print("Origin")
        case Point(x=0, y=y):
            print(f"Y={y}")
        case Point(x=x, y=0):
            print(f"X={x}")
        case Point():
            print("Somewhere else")
        case _:
            print("Not a point")
            
打印效果:Origin

points列表的匹配:

python 复制代码
def match_points():
    points = [Point(0,5),Point(0,7)]
    match points:
        case []:
            print("No points")
        case [Point(0, 0)]:
            print("The origin")
        case [Point(x, y)]:
            print(f"Single point {x}, {y}")
        case [Point(0, y1), Point(0, y2)]:
            print(f"Two on the Y axis at {y1}, {y2}")
        case _:
            print("Something else")
            
打印效果:Two on the Y axis at 5, 7

带条件的match:

python 复制代码
def match_if():
    point = Point(x=5, y=5)
    match point:
        case Point(x, y) if x == y:
            print(f"Y=X at {x}")
        case Point(x, y):
            print(f"Not on the diagonal")
打印效果:Y=X at 5

枚举match:

python 复制代码
from enum import Enum
class Color(Enum):
    RED = 'red'
    GREEN = 'green'
    BLUE = 'blue'

def match_enum():
    color = Color('green')
    match color:
        case Color.RED:
            print("I see red!")
        case Color.GREEN:
            print("Grass is green")
        case Color.BLUE:
            print("I'm feeling the blues :(")
打印效果:Grass is green

虽然一枚小小码农,不过也在向阳努力着,本人在同步做读书故事的公众号,欢迎大家关注【彩辰故事】,谢谢支持!~

相关推荐
学步_技术4 分钟前
Python编码系列—Python工厂方法模式:构建灵活对象的秘诀
开发语言·python·工厂方法模式
秋秋秋叶16 分钟前
Python学习——【2.3】for循环
python·学习
会发paper的学渣32 分钟前
python 单例模式实现
开发语言·python·单例模式
学步_技术40 分钟前
Python编码系列—Python桥接模式:连接抽象与实现的桥梁
开发语言·python·桥接模式
柴华松42 分钟前
GPU训练代码
开发语言·python
Echo_Lee01 小时前
C#与Python脚本使用共享内存通信
开发语言·python·c#
python之行1 小时前
python 环境问题
开发语言·python
hakesashou1 小时前
python怎么写csv文件
开发语言·python
欧阳枫落1 小时前
pip 换源
开发语言·python·pip