python基础语法2

python基础语法2

了解整体内容可以从基础语法1开始,第2天了,开始上代码片段。
本篇主要内容:控制流语句if、for、match等。


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

# 启动方法,要写到函数方法的下面
if __name__ == '__main__':
    print_hello('PyCharm')
    
打印效果:hello, PyCharm
  1. if语句
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循环
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,实际存储并不是列表,所以节省空间。
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 子句就不会执行。
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 语句不执行任何动作,可占位。
while True:
    pass
def initlog():
    pass
  1. match语句
    一个主语值与多个字面比较的例子:
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

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

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

类组织数据的方式:

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列表的匹配:

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:

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:

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

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

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值