python 笔记 2

本贴最后更新于 2534 天前,其中的信息可能已经时移世异

一些符号

%s 和 %r


s = "hello \nworld"

print("> %s" % s)

print("> %r" % r)

'''

输出:

> hello 

world

> 'hello \nworld'

'''

%s 使用的是 str(),%r 使用 repr()。

str()返回字符串,上述例子他返回的是:'> hello \nworld'

repr()返回字符串的显示(repr() is meant to generate representations which can be read by the interpreter ),上述例子他返回的是:"'hello \nworld'"。

感觉 repr()就是返回了表达式?所以可以直接被 eval()使用?

is 和==

这个东西百度一下都是些啥玩意?!(顺便吐槽:这么多写博客的人自己都不知道自己在写什么,到处都是 copy,写的东西算是解释又解释不清楚。)最后还是 google 了以后在 stackoverflow 找到了一个精准简短的解释:

is will return True if two variables point to the same object, == if the objects referred to by the variables are equal.

modules

系统的模块


# test_mo.py文件

import sys

my_list = sys.argv

print(my_list)

在终端输入 python test_mo.py AAA BBB

终端会输出


['test_mo.py','AAA','BBB']

sys 是 python 自带的 module,就是 System。之后的 argv 是 sys 的自带变量,用 list 的形式存放了命令行中输入的所有参数。

这是将外部的变量传给脚本的其中一个办法。

自定义的模块


# 这是my_square.py文件

def square(x):

    return x * x

if __name__ == "__main__":

    print("m_ex.py:function",square(11))

###########################################

#这是my_test.py文件

import my_square

print(my_square.square(5))

#输出 25

关于 io


with open('xxx/xxx') as f:

    print(f.read())

    f.seek(0)

    for line in f.readlines():

        print(line.strip())

这种写法就可以不用打 close()了,with 会帮助调用 close()。

seek()用来指定位置,strip()用来删除字符串两端的特殊符号。readlines()返回的是 list of line。

os 模块:


import os

os.path.split()

os.path.splitext()

os.path.join()

os.remove()

os.rename()

os.listdir()

一些目前感觉很有用的 os 的函数。

异常处理


def test():

    try:

        print('this is try')

        raise Exception('error')

        return 'try'

    except Exception:

        print('this is except')

        return 'except' 

    finally:

        print('this is finally')

        return 'finally'

print(test())

'''

输出:

this is try

this is except

this is finally

finally

'''

出现异常以后转入 except。

不管怎么样最后都会转入 finally,如果前面两个区段有 return,还是先转入 finally,finally 有 return 执行 return 退出,没有 return 就转出向上一个区段,执行 return。

  • Python

    Python 是一种面向对象、直译式电脑编程语言,具有近二十年的发展历史,成熟且稳定。它包含了一组完善而且容易理解的标准库,能够轻松完成很多常见的任务。它的语法简捷和清晰,尽量使用无异义的英语单词,与其它大多数程序设计语言使用大括号不一样,它使用缩进来定义语句块。

    535 引用 • 672 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...