• Python从入门到入土-基础语法


    看不见的开始和结束

    作用域是编程语言里的一个重要的概念,特别是块作用域,编程语言一般会使用明确的符号标记一个作用域的开始和结束。
    例如 C、C++、Java、C#、Rust、Go、JavaScript 等常见语言都是用"{“和”}"来标记一个块作用域的开始和结束:

    // 这是一个C语言程序
    if(i<10){
        if(i<5){
            print("win more!");
        }else{
            print("win");
        }
    }else{
        print("loose");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    // 这是一个 Rust 语言程序
    if i<10 {
        if i<5 {
            println!("win more!");
        }else{
            println!("win");
        }
    }else{
        println!("loose");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    而 Python 程序则是用缩进来表示块作用域的开始和结束:

    # 这是一个 Python 程序
    if i<10:
        if i<5:
            print("win more!")
        else:
            print("win")
    else:
        print("loose")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    Python 对缩进有严格的要求,同一个源文件里,缩进必须保持一致,例如都是2个空格或者4个空格。Python 这么做的理由是使用缩进更简洁,同时不用考虑"{"要放在哪一行,而且是用缩进足够Python解释器正确解析。但是使用缩进如果没有编辑器自动检测和格式化也会带来一些不必要的麻烦。

    函数

    函数是代码复用的最简单形式。在第一章里我们已经多次不经介绍地使用了函数来组织代码。现在可以系统认识下函数的参数。

    # -*- coding: UTF-8 -*-
    def dump(index, default=0, *args, **kw):
        print('打印函数参数')
        print('---')
        print('index:', index)
        print('default:', default)
        for i, arg in enumerate(args):
            print(f'arg[{i}]:', arg)
        for key,value in kw:
            print(f'keyword_argument {key}:{value}')
        print('')
    
    if __name__=='__main__':
        dump(0)
        dump(0,2)
        dump(0,2,"Hello","World")
        dump(0,2,"Hello","World", install='Python', run='Python Program')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    Python函数的参数十分灵活,例如上面的例子:

    • index: 按顺序位置指定的参数
    • default=0: 带有默认值的参数
    • *args: 0个或多个可选的参数
    • **kw: 0个或多个关键字参数

    类定义和使用如下:

    class KeyValueSet:
        def __init__(self) -> None:
            self.dict = {}
    
        def set(self, key, value):
            self.dict[key] = value
    
        def get(self, key):
            return self.dict.get(key)
    
        def keys(self):
            return self.dict.keys()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    from com.zjq.python.base.classuse.KeyValueSet import KeyValueSet
    
    
    class GuessSentenceGame:
        def __init__(self):
            self.kv = KeyValueSet()
            self.score = 0
    
    
        def setup(self, sentences):
            for sentence in sentences:
                self.append(sentence)
    
        def append(self, sentence):
            cut_pos = sentence.find(' ')
            first_word, rest = sentence[0:cut_pos], sentence[cut_pos + 1:].strip()
            self.kv.set(first_word, rest)
    
        def guess(self, first_word):
            ret = self.kv.get(first_word)
            if ret is None:
                return 1, None
            else:
                return 0, ret
    
        def run(self):
            self.score = 0
            for first_word in self.kv.keys():
                ret = input("猜一猜下半句是什么? {} -> :".format(first_word))
                err, value = self.guess(first_word)
                if err == 0:
                    print('你太厉害了,这都能猜得到!+10分!')
                    self.score += 10
                else:
                    self.score -= 2
                    print('哈哈,肯定猜不到得啦:{}->{},扣除2分!'.format(first_word, value))
            print('游戏结束,你本次游戏得分:', self.score)
    
    
    if __name__ == '__main__':
        sentences = [
            "hello world",
            'monkey king',
            'tomorrow is another day',
            "good bye"
        ]
    
        game = GuessSentenceGame()
        game.setup(sentences)
        game.run()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    继承使用如下:

    from com.zjq.python.base.classuse.KeyValueSet import KeyValueSet
    
    class HashKeyValueSet(KeyValueSet):
        def __init__(self) -> None:
            super().__init__()
    
        def hset(self, hash_key, key, value):
            self.set(hash_key, {key: value})
    
        def hget(self, hash_key, key):
            hash_set = self.get(hash_key)
            if hash_set is None:
                return None
            else:
                return hash_set.get(key)
    
        def hkeys(self, hash_key):
            hash_set = self.get(hash_key)
            if hash_set is None:
                return []
            else:
                return hash_set.keys()
    
    if __name__ == '__main__':
        from com.zjq.python.base.classuse.HashKeyValueSet import HashKeyValueSet
        hashset = HashKeyValueSet()
    
        hashset.hset('puzzle', 'hello', 'world!')
        hashset.hset('puzzle', 'monkey', 'king!')
        hashset.hset('puzzle', 'tomorrow', 'is another day')
        hashset.hset('puzzle', 'good', 'bye!')
    
        keys = hashset.hkeys('puzzle')
        for key in keys:
            ret = input("猜一猜下半句是什么? {} -> :".format(key))
            value = hashset.hget('puzzle', key)
            if ret == value:
                print('你太厉害了,这都能猜得到!')
            else:
                print('哈哈,肯定猜不到得啦:{}->{}'.format(key, value)).
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    顺序语句

    def test():
        print("* 如果想计算一个长方形的面积")
        print("* 那就先定义长宽,例如:x = 10, y=20")
        print("* 紧接着,我们计算长方形的面积:s = x * y")
    
        x = 10
        y = 20
        s = x * y
    
        print("* 现在可以输出结果了,该长方形的面积是:{}".format(s))
    
    if __name__ == '__main__':
        test()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    循环语句

        # 使用 for 遍历打印列表信息
        list = [
            {
                "id": 966024429,
                "number": 2341,
                "title": "Question about license.",
                "body": "I would like to create a [winget](https://github.com/microsoft/winget-cli) package for jq. 🙏🏻"
            },
            {
    
                "id": 962477084,
                "number": 2340,
                "title": "visibility of wiki pages",
                "body": "The visibility of wiki pages to search engines is generally limited; for example, the search result for \"jq Cookbook\" looks like this:"
            }
        ]
        # 循环方式1
        i = 0
        for item in list:
            print('')
            print("## 第{}条信息".format(i))
            print("* id: {}".format(item['id']))
            print("* number: {}".format(item['number']))
            print("* title: {}".format(item['title']))
            print("* body: {}".format(item['body']))
            i += 1
        #循环方式2
        for i in range(len(list)):
            item = list[i]
            print('')
            print("## 第{}条信息".format(i))
            print("* id: {}".format(item['id']))
            print("* number: {}".format(item['number']))
            print("* title: {}".format(item['title']))
            print("* body: {}".format(item['body']))
        # 循环方式3
        for i, item in enumerate(list):
            print('')
            print("## 第{}条信息".format(i))
            print("* id: {}".format(item['id']))
            print("* number: {}".format(item['number']))
            print("* title: {}".format(item['title']))
            print("* body: {}".format(item['body']))
    
        # while循环方式1
        i = 0
        while i < len(list):
            item = list[i]
            print('')
            print("## 第{}条信息".format(i))
            print("* id: {}".format(item['id']))
            print("* number: {}".format(item['number']))
            print("* title: {}".format(item['title']))
            print("* body: {}".format(item['body']))
            i += 1
    
        # while循环方式2
        i = 0
        while True:
            item = list[i]
            print('')
            print("## 第{}条信息".format(i))
            print("* id: {}".format(item['id']))
            print("* number: {}".format(item['number']))
            print("* title: {}".format(item['title']))
            print("* body: {}".format(item['body']))
            i += 1
            if i == len(list):
                break
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69

    数据类型

    if __name__ == '__main__':
        # 字符串
        print("字符串加法" + "字符串加法")
        print("字符串乘法" * 3)
        print(",".join(["字符串数组的聚合", "字符串数组的聚合", "字符串数组的聚合"]))
    
        print("双引号字符串")
        print('单引号字符串')
        triple = '''三引号字符串'''
        print("双引号字符串里的单引号: 'hello world!'")
        print('单引号字符串里的双引号: "hello world!"')
    
        # 列表
        array = []
        array.append(10)
        array.append(20)
        array.pop(0)
        array.append(30)
        array.append(40)
        array.pop(0)
    
        # 元数组
        tuple = ('红色', '绿色', '蓝色')
        for element in tuple:
            print(element)
    
        import math
        r, g, b = 0.6, 0.8, 0.3
        hr, hg, hb = (math.pow(r, 3 / 2), math.pow(g, 4 / 5), math.pow(b, 3 / 2))
        print("使用《黑客帝国》绿色滤镜算法计算后的颜色[0-1]:({}, {}, {})".format(hr, hg, hb))
    
        print("不带括号的也是元组:")
        r, g, b = 0.6, 0.8, 0.3
        print("普通颜色[0-1]:({}, {}, {})".format(r, g, b))
        
        # 字典(等同于java中的map)
        map = {}
        map['name'] = "monkey"
        map['age'] = 25
        map['tags'] = "猴子"
        map['tags'] = ['程序员', '户外达人']
        map['profile'] = {'info1': "test", "info2": "test"}
    
        print(map['tags'])
        print(map['profile'].get("info3"))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    内置类

    #内置类的使用,列表元素去重+过滤小于3的元素
    
    # 去重方式
    def remove_duplicates(items):
        res = list(set(items))
        return res
    
    # 过滤方式1
    # def filter_element(items, bound):
    #     res = [item for item in items if item < bound]
    #     return res
    
    # 过滤方式2
    def filter_element(items, bound):
        res = [item for item in items if item < bound]
        return res
    
    
    if __name__ == '__main__':
        a = [1, 2, 3, 4, 4, 5, 5]
        print('输入: {}'.format(a))
    
        res = remove_duplicates(a)
        print('去重后的结果:{}'.format(res))
    
        bound = 3
        res = filter_element(a, bound)
        print('过滤小于{}的元素:{}'.format(bound, res))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    常用内置方法

    
    
    # 内置方法
    if __name__ == '__main__':
    
        # assert abs(-1) == 1
        # assert max(10, 100) == 100
        # assert min(10, 100) == 10
        # assert round(3.5) == 3
        # assert pow(2, 4) == 16
        # assert float(1) == 1.0
    
        assert 'count' in dir([])
        assert hash("a") == hash(chr(97))
        assert type({}) == type({'a': 1})
    
        assert all([True, True]) == True
        assert any([True, False]) == True
        assert bool({}) == False
        assert callable(abs) == True
    
        seasons = ['Spring', 'Summer', 'Fall', 'Winter']
        assert len(seasons) == 4
    
        shortcut = list(map(lambda s: s[0], seasons))
        assert shortcut == ['S', 'S', 'F', 'W']
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    本文内容到此结束了,
    如有收获欢迎点赞👍收藏💖关注✔️,您的鼓励是我最大的动力。
    如有错误❌疑问💬欢迎各位大佬指出。
    主页共饮一杯无的博客汇总👨‍💻

    保持热爱,奔赴下一场山海。🏃🏃🏃

    在这里插入图片描述

  • 相关阅读:
    linux下usleep函数对CPU占用率的影响
    基于粒子群优化算法、鲸鱼算法、改进的淘沙骆驼模型算法(PSO/SSA/tGSSA)的微电网优化调度(Matlab代码实现)
    在字节跳动,一个更好的企业级SparkSQL Server这么做
    真嘟假嘟?!这么清晰简单的字符函数和字符串函数!!!
    JAVA毕业设计分享网站计算机源码+lw文档+系统+调试部署+数据库
    程序员自由创业周记#35:外包、技术选型和卖房
    支持CAN FD的Kvaser PCIEcan 4xCAN v2编码: 73-30130-01414-5如何应用?
    发布有关陕西省工程师职称评审申报细节注意事项
    设计模式学习(二十二):解释器模式
    maven-plugin-shade 详解
  • 原文地址:https://blog.csdn.net/qq_35427589/article/details/126170666