python之print()函数

引言:
在上一周内我作为助教,有幸能免费听Alex老师的直播一对一教学,课程的主题是python基础,但对我这个已经熟悉过python语法(但使用方面很生疏)的人来说,也是有不少干货的,这个系列博客就上课过程中,一些对我有帮助的内容进行复述总结,算是基于我消化吸收后的再创作吧。而原课程的录像以及ppt和代码则作为csdn的付费课程发布,有兴趣的同学可以自行购买课程,这里附上链接:https://edu.csdn.net/course/detail/20599

print()函数

学习过c语言的朋友们一定一眼就看的出print()函数大概是做什么用的。c语言中与其相似的printf()函数及大致用法如下

#include<stdio.h>
int main(void){
    printf("这是一串字符")return 0;
      }

使用printf()很麻烦,以上所有代码一起出现,才能使终端出现“这是一串字符”,而且也很功能单一。

那么我们来看看python中的print()函数

print()

我们首先在pycharm中输入一个 ‘print()’ ,然后按住键盘上的ctrl键同时鼠标左击输入的 ‘print()’ ,这样就打开所有库函数的源代码 如下图:
在这里插入图片描述
找到print()

def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
    """
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
    """
    pass

英语学的还不错的同学一目了然,不过我还是一一解释,来给大家看

  • print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
    这是print函数的调用格式,括号里面是其参数。
  • Prints the values to a stream, or to sys.stdout by default. 在流中或默认的终端输出值,
  • Optional keyword arguments:可选择的参数解析。
  • file: a file-like object (stream); defaults to the current sys.stdout.输出对象(流)比如一个文件,默认为终端。
  • sep: string inserted between values, default a space.在值之间插入字符,默认为一个空格。
  • end: string appended after the last value, default a newline.在最后一个值后添加字符,默认为一个换行符。
  • flush: whether to forcibly flush the stream.是否释放流。

具体例子可以在视频课程中找到,此处赠上b站免费版课程(无ppt和代码):https://t.bilibili.com/400013329599284093?tab=2

其中有一个比较有趣的例子是:
用python实现打印机功能

import time

def printer(content,delay):
    for char in content:
        print(char, end='', flush=True)
        time.sleep(delay)

printer('有内鬼,终止交易!',0.3)   

针对这个例题留下的作业是:完成一个 转动加载图案。完成代码如下:

import time

def printer(content,delay):
    for char in content:
        print(char, end='', flush=True)
        time.sleep(delay)
        print('\b',end='',flush=True)
for i in range (100000000):
    printer('/——\\——', 0.00000000000001)

结语: 更详细的讲解见视频课程哦:https://www.bilibili.com/video/BV1Qg4y1i7xT

猜你喜欢

转载自blog.csdn.net/qq_45797026/article/details/106724822