print(value, ..., sep=' ', end='\n',file=sys.stdout, flush=False)
print()函数本身用于输入value数据到标准输出【控制台界面】
sep参数控制分隔符号~
end参数用于控制输出后的显示结果是否需要换行,默认换行
file参数~默认指定了stdout标准输出
input(prompt=None, /) prompt参数:提示信息
>>> dir(list) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> help(list.insert) Help on method_descriptor: insert(self, index, object, /) Insert object before index.
def 函数名称(函数中代码执行需要的参数列表): 函数中执行的代码块 [return 返回值] 文档中:如果在操作语法说明中出现了方括号~表示这一部分内容是可选的
def test(): 函数中的代码 test() 调用执行test函数,执行test函数中的代码 test2 = test 将函数test赋值给变量test2,并不会执行函数test test2() 执行test2函数~ test2中存放的是test-> 执行test()函数
def test(name): print("用户的名称是:", name) test("tom") #执行test函数~需要一个数据name
def test(name): print(name)
test("tom")
def test(a, b, c, d): print(.....) 操作过程中,调用执行时~实际参数按照形式参数的前后顺序[位置]依次赋值 test(1,2,3,4)
def test(a, b, c, d=100): print(.....) 操作过程中,函数声明中~某个形式参数可以直接赋值~该形式参数就是默认值参数;默认值参数可以在调用时不传递数据~使用默认数据进行运算。 test(1,2,3) d自动赋值默认100运算 test(1,2,3,4) d赋值4进行运算 注意:默认值参数一般放在最后面
def test(a, *args): args: arguments 参数 print(.....) 操作过程中,可以通过符号*,声明某个可以接受多个数据的可变参数~ 可变参数可以接受0~n个数据。 test(1,2,3) a赋值1,args赋值(2,3) test(1,2,3,4) a赋值1, args赋值(2,3,4) 可变参数可以将接受到的多个参数~自动封装成元组进行操作。自动封装过程~某些资料:自动封箱/自动装箱 注意:可变参数一般放在最后面
def test(a, **kwargs): kwargs : keyword arguments 关键字参数 print(.....) 操作过程中,可以通过符号**,声明某个可以接受多个key-value键值对数据,并且自动装箱成字典接受到函数中进行处理 test(1, name="jerry", age=12) a赋值1,kwargs赋值{"name": "jerry", "age": 12} 注意:关键字参数一般放在最后面
def test(*args, **kwargs): pass *args可以接受任意多个的单个数据 **kwargs可以接受任意多个的key-value键值对数据 按照函数调用规范,单个数据放在前面,key-value数据放在后面。所以上面的参数列表:万能参数,可以接受任意数据当成函数的参数进行处理。
def test(*, name, age): pass 声明在符号*后面的所有参数,都是强制关键字参数~ 理由?为什么要用它? 特点:一旦声明~函数中定义了的参数名称,必须在调用的时候使用它们作为key值 test(name="tom", age=100) right test(x="jerry", y=10) error 理由:极大限度的提升代码的可读性
def test(): # TODO 注释【功能描述、时间、作者】 pass 通过pass占位符,让声明但是还没有实现的函数~不报错。 不影响整体项目的进度。 TODO注释~一种特殊的注释,表示待开发功能 常规的IDE工具基本都集成了TODO注释的操作。
>>> dir(str) ['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal','isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper','join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
s = “我叫%s, 今年%d” % (“jerry”, 30)
s = "我叫{}, 今年{}".format("tom", 30) s = "我叫{name}, 今年{age}".format(name="tom",age=30) s = "我叫{name}, 今年{age}".format(age=30, name="tom")
name = "jerry" age = 19 s = f"我叫{name}, 今年{age}"
s[start, stop, step=1] s是个字符串 start开始位置 stop结束位置 step步长 >>> s = "he l lo python1901" 0123456....... >>> s = " h e l lo python1901" 0 1 2 s[1:] -> e l lo python1901
文件操作:编程语言中最重要的一个环节。 涉及到的是程序和操作系统之间的数据交互。 IO操作: I:input输入:将文件中的数据输入到程序中 O:output输出:将程序中的数据存储到文件中
>>> dir(os) ['abc', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'walk', 'write'] >>> dir(os.path) ['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_abspath_fallback', '_get_bothseps', '_getfinalpathname', '_getfullpathname', '_getvolumepathname', 'abspath', 'altsep', 'basename', 'commonpath', 'commonprefix', 'curdir', 'defpath', 'devnull', 'dirname', 'exists', 'expanduser', 'expandvars', 'extsep', 'genericpath', 'getatime', 'getctime', 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile', 'islink', 'ismount', 'join', 'lexists', 'normcase', 'normpath', 'os', 'pardir', 'pathsep', 'realpath', 'relpath', 'samefile', 'sameopenfile', 'samestat', 'sep', 'split', 'splitdrive', 'splitext', 'stat', 'supports_unicode_filenames', 'sys'] os.path.getsize() 获取文件大小 os.path.basename() 基础路径 os.path.exists()判断某个文件是否存在 os.path.isdir() 判断是否文件夹 os.path.isfile() 判断是否文件 os.path.join() 拼接路径
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Open file and return a stream. Raise OSError upon failure. 打开一个文件并且得到一个文件数据流,如果操作失败就会出现OSError异常 open函数:操作文件的一个函数 file参数:要操作的文件名称:绝对路径/相对路径 mode参数:操作方式 buffering参数:缓存 encoding参数:编码
1.存储 字典:d = dict() 字典-> 字符串 with open(file,"w") as f: f.write(字符串)存储到文件中 最终:文件中存储的是字符串数据 1. 将程序中的字典数据,转换成字符 串存储到文件中串存储到文件中 users = {'admin': {'username': 'admin', 'password': '123', 'nickname': '老刘'}} 类型能否之间转换字符串? users_str = str(users) 存储到文件中 with open('./data/2.1.text', 'w') as file: file.write(users_str)
with open(file, 'r') as f: data = f.read() 读取数据,将文件中的字符串数据,读取到程序中->问题:字符串依旧是字符串,不是python对象 eval函数:将一个字符串转换成python表达式 2. 将文件中的字符串数据,读取到程序中 with open('./data/2.1.text', 'r') as file: users = file.read() print(users, type(users)) # 将字符串数据,转换成字典:该字符串的格式~和python中的字典的表达式一致 users = eval(users) print(users, type(users)) print(users.get('admin'))
# 准备操作的数据 users = {'admin': {'username': 'admin', 'password': '123', 'nickname': '老刘'}} # 1. 将程序中的数据,直接存储到文件中 # json模块的操作 with open('./data/3.1.json', 'w') as file: json.dump(users, file) 打开一个文件~ 通过json.dump函数,将该对象,添加到文件中
# 2. 将文件中的数据,读取到程序中 with open('./data/3.1.json', 'r') as file: users = json.load(file) print(users, type(users))