Python基础语法

举报
共饮一杯无 发表于 2022/09/27 09:31:29 2022/09/27
2.3k+ 0 1
【摘要】 看不见的开始和结束作用域是编程语言里的一个重要的概念,特别是块作用域,编程语言一般会使用明确的符号标记一个作用域的开始和结束。例如 C、C++、Java、C#、Rust、Go、JavaScript 等常见语言都是用"{“和”}"来标记一个块作用域的开始和结束:// 这是一个C语言程序if(i<10){ if(i<5){ print("win more!"); }e...

看不见的开始和结束

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

// 这是一个C语言程序
if(i<10){
    if(i<5){
        print("win more!");
    }else{
        print("win");
    }
}else{
    print("loose");
}
// 这是一个 Rust 语言程序
if i<10 {
    if i<5 {
        println!("win more!");
    }else{
        println!("win");
    }
}else{
    println!("loose");
}

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

# 这是一个 Python 程序
if i<10:
    if i<5:
        print("win more!")
    else:
        print("win")
else:
    print("loose")

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')

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()
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()

继承使用如下:

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)).

顺序语句

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()

循环语句

    # 使用 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

数据类型

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"))

内置类

#内置类的使用,列表元素去重+过滤小于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))

常用内置方法



# 内置方法
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']
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。