Python 基础【第三篇】输入和输出

 

这里我们创建一个python(pytest)脚本用于学习测试(以后都为这个文件,不多做解释喽),这个文件必须要有执行权限的哈

1.创建pytest并赋予执行权限

[root@fengyuba_server py]# touch pytest
[root@fengyuba_server py]# chmod +x pytest

2. 基本输出“print

[root@fengyuba_server py]# vim pytest
#指定python可执行程序路径
#!/usr/bin/python
#打印一个字符串
print 'this is python'
#打印一个运算
print '100+200 =',100+200

运行pytest查看输出结果

[root@fengyuba_server py]# ./pytest
this is python
100+200 = 300

这个简单的输出应该木啥问题吧,

这里有个问题要说下:

不知道大家注意到没有print '100+200 =',100+200 中 “,” 这个符号 我测试了下这个符号必须加!用意为:连接字符串和命令同时也是空格输出。

另外还有一点 就是python3版本print的格式有变化格式如下

>>>print (“string”)

3.python基本输入input()/raw_input()

基本输出很简单直接print就行那么如何读取输入呢?python根据内建函数input、raw_input来进行读取

格式如下:

[Number]=raw_input(‘string’)
[Number]=input(‘string’)

上面的number为变量 string 为提示字符串 raw_input/input会将读取到的值输出给Number

既然raw_input、input 都可以读取输入那么他们的区别是什么呢?

input:可以输入合法的表达式,比如输入1+2 而且它还会识别int格式,也就是说你输入数字的话不需要转换即可进行运算操作

raw_input:可以输入任意数值不报错,输入的数值均识别为字符串,也就是说你输入数字的话需要转换才可进行运算操作

具体举个例子大家来看下:

3.1、Input

举例:输入1+2查看输出结果

#!/usr/bin/python
number1=input('please input your number1:')
print number1
[root@fengyuba_server py]# ./pytest
please input your number1:1+2
3

3.2、raw_input

举例:运行脚本提示输入值、然后输出该值

[root@fengyuba_server py]# vim pytest
#!/usr/bin/python
number1=int(raw_input('please input your number1:'))
number2=int(raw_input('please input your number2:'))
print 'your nmuber is:',number1+number2
[root@fengyuba_server py]# ./pytest
please input your number1:15
please input your number2:10
your nmuber is: 25

4. 字符串符号 引号

在python里有三种引号可以使用,分别是:

单引号(’ ’)、双引号 ("")、三引号(""" """)

三种方式基本上差不多都是输出字符串的下面我们看下三种输出效果

>>> print('this is test txt')
this is test txt
>>> print("this is test txt")
this is test txt
>>> print("""this is
test txt""")
this is
test txt

上面可以看出 单引号和双引号效果一样 三引号 比较个性点

下面我们来看下三种引号的区别

4.1. 单引号和双引号是可以互换的区别不太大,他们的区别在于两种符号混用的时候,如下面例子所示

>>> print('test this's')
SyntaxError: invalid syntax
>>> print("test this's")
test this's
>>> print("this is "test"")
SyntaxError: invalid syntax
>>> print('this is "test"')
this is "test"

通过上面的例子大家很清楚了吧,就是单引号中不能再包含单引号、双引号中不能再包含双引号(除非使用转义符”\”将符号转义),不然python是无法识别单引号和双引号的开始和结尾的

4.2. 三引号

可以换行,适合于输出文本

注:就换行的问题其实单引号和双引号也是可以做到的只是方式不同,单引号/双引号的 换行方式如下:

添加 “\n”

>>> print('this is \n test')
this is
test

OK!上面我们学习了python的基本环境 和 python的输入和输出 下面我们来做一个案例检验检验我们的成果吧!

案例:

案例:执行脚本输入两个数字并对数字进行相加得出结果进行打印,要求第一个数字利用函数INPUT 通过表达式得出、第二个数值要求利用raw_input

[root@fengyuba_server py]# vim pytest
#!/usr/bin/python
#利用input获取第一个值
number1=input('please input your number1:')
#利用raw_input获取第二个值并int初始华为整数
number2=int(raw_input('please input your number2:'))
#打印出两个值的计算结果
print 'sumber=',number1+number2
#执行脚本查看执行结果
[root@fengyuba_server py]# ./pytest
please input your number1: 1+15
16
please input your number2: 16
sumber= 32

OK! 上面就是脚本内容以及输出结果怎么样?有点成就感吧!

作者:Alan
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利!
原文地址:https://www.cnblogs.com/Alanpy/p/5029567.html