有人可能会想,连2-1和2-2这样的题目都回答,够无聊的啊。
因为现在处于并长期处于成为大师的第一阶段------守的阶段
2-1
>>> a= '123'
>>> a
'123'
>>> print (a)
123
a是字符串123,如果格式化输出有问题报如下错误:
>>> print ('a is %d'% a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str
这样就正确了。
>>> print ('a is %s' % a)
a is 123
a如果是×××:
>>> a = 123
>>> print ('a is %s'% a)
a is 123
>>> a
123
>>> print (a)
123
>>> print ('a is %d' %a )
a is 123
print和交互式解释器显示对象的区别:
print调用str()函数显示对象,而交互式解释器则调用repr()函数来显示对象。
2-2
(a) 用来计算1+2x4的结果
(b)作为脚本什么都不输出
©预期的一样,因为这个脚本没有print输出
(d)在交互式系统中有输出,如下:
>>> #!/usr/bin/env python
... 1 + 2 * 4
9
>>>
(e)脚本改进如下:
#!/usr/bin/env python
print (1 + 2 * 4)
输出结果如下:
2-3
在python3中/是真正的除法,//是地板除(取整,取比实际除法得到的结果小最近的整数)
2-4
脚本:
[root@centos7_01 P36practise]# cat 2_4.py
#!/usr/bin/env python
x = raw_input("please input a string:\n")
print x
运行结果:
[root@centos7_01 P36practise]# python 2_4.py
please input a string:
ad cd
ad cd
2-5
[root@centos7_01 P36practise]# cat 2-5.py
#!/usr/bin/env python
print
print ("using loop while:")
i = 0
while i < 11 :
print i
i += 1
print
print ("*"*50)
print ("using loop for:")
for i in range(11):
print i
print
运行结果:
[root@centos7_01 P36practise]# python 2-5.py
using loop while:
0
1
2
3
4
5
6
7
8
9
10
**************************************************
using loop for:
0
1
2
3
4
5
6
7
8
9
10
2-6
[root@centos7_01 P36practise]# cat 2-6.py
#!/usr/bin/env python
import sys
print ("if you want to exit the program please insert q\n")
i = raw_input("please input a number:\n")
def fun(i):
try:
i = int(i)
except ValueError:
print ("WARNING !!! %s is not permit \nplease input a num or 'q':\n")%i
sys.exit()
if i < 0:
print "judge:%d is negative" % i
print
elif i == 0:
print "judge:%d is zero" % i
print
else:
print "judge:%d is positive" % i
print
while i != 'q':
fun(i)
i = raw_input("please input a number:\n")
else:
sys.exit()
运行结果:(输入ctrl+c退出)
[root@centos7_01 P36practise]# python 2-6.py
if you want to exit the program please insert q
please input a number:
1
judge:1 is positive
please input a number:
-1
judge:-1 is negative
please input a number:
0
judge:0 is zero
please input a number:
^CTraceback (most recent call last):
File "2-6.py", line 27, in <module>
i = raw_input("please input a number:\n")
KeyboardInterrupt
输入q退出:
[root@centos7_01 P36practise]# python 2-6.py
if you want to exit the program please insert q
please input a number:
-1