给宝宝讲python:(一)、输入输出

给宝宝讲python:基础

输入or输出?

Input

输入说简单也简单,说不简单也不简单,input something表示提示文字,可以不写,可以试试看是什么样子的哟。

In [31]: param = input('Input something:')                
Input something:0303                                      
                                                          
In [32]: type(param)                                      
Out[32]: str                                              
                                                          
In [33]: param2 = input('Input something:')               
Input something:baby                                      
                                                          
In [34]: type(param)                                      
Out[34]: str                                              

主要要掌握以下一个知识点,就是,无论是字符串,字符,还是数字,input 函数都会在值的左右加上一个引号(“”),所以可以使用eval函数,你现在不用具体了解eval的用法,知道它可以让用户输入的数字保持int类型就行了。

In [40]: param3 = eval(input('Input something:'))
Input something:329

In [41]: type(param3)
Out[41]: int

Print

我们先看一下help(print)之后的输出。

In [43]: help(print)
Help on built-in function print in module builtins:

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.

可以看print函数后面的参数有file,sep,end,flush

file:类文件对象(stream); 默认为当前的sys.stdout。
sep:在值之间插入的字符串,默认为空格。
end:在最后一个值后附加的字符串,默认为换行符。
flush:是否强制刷新流。

举个例子,如下:

In [48]: print('output file', 'space string', sep='-xixi-', end='/baby')
output file-xixi-space string/baby

在这里插入图片描述
下面是最常见的输出情况,这里双引号和单引号在Python中,没有区别,记住这样多就够了。

In [1]: print('hello world')
hello world

In [2]: print("hello world")
hello world

格式化输出,使用format

In [13]: print('基础format格式化输出')
基础format格式化输出   
In [14]: print('{}'.format('hello world'))
hello world        
In [15]: print('带有编号:{0}{1}{0}{2}'.format('hello ', 'world,', 'my baby.'))
带有编号:hello world,hello my baby.   
In [19]: print('带有关键字的:{first},{end}'.format(end = 'baby', first = 'hello'))
带有关键字的:hello,baby     
In [30]: print('保留一位小数输出:{:.1f}'.format(190.32))
保留一位小数输出:190.3                 

这里不具体介绍另外一种格式化输出方式 %,但是还是需要看懂,就简单说明一下,

待更新。

发布了30 篇原创文章 · 获赞 21 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_41288824/article/details/101001050