python核心編程第二版 第二章練習題解答 未完待續
阿新 • • 發佈:2019-04-20
ive posit turn 求和 image env form you per
(b)作為腳本什麽都不輸出
(c)預期的一樣,因為這個腳本沒有print輸出
(d)在交互式系統中有輸出,如下:
有人可能會想,連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的結果
(c)預期的一樣,因為這個腳本沒有print輸出
(d)在交互式系統中有輸出,如下:
>>> #!/usr/bin/env python
... 1 + 2 * 4
9
>>>
(e)腳本改進如下:
#!/usr/bin/env python
print (1 + 2 * 4)
輸出結果如下:
![](https://s1.51cto.com/images/blog/201904/20/791289dff32149259a72c171344afb03.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)
2-3
在python3中/是真正的除法,//是地板除(取整,取比實際除法得到的結果小最近的整數)
2-4
腳本:
[[email protected]_01 P36practise]# cat 2_4.py
#!/usr/bin/env python
x = raw_input("please input a string:\n")
print x
運行結果:
[[email protected]_01 P36practise]# python 2_4.py
please input a string:
ad cd
ad cd
2-5
[[email protected]_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
運行結果:
[[email protected]_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
[[email protected]_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退出)
[[email protected]_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退出:
[[email protected]_01 P36practise]# python 2-6.py
if you want to exit the program please insert q
please input a number:
-1
judge:-1 is negative
please input a number:
1
judge:1 is positive
please input a number:
q
[[email protected]_01 P36practise]#
2-7
[[email protected]_01 P36practise]# cat 2-7.py
#!/usr/bin/env python
#encoding:utf8
import sys
str = raw_input("please input a string:\n")
for i in str:
print i
print "*"*50
print
print "網上搜來的方法:\n"
i = 0
while i < len(str):
print str[i]
i += 1
print "野路子\n"
i = 0
while str:
try:
print str[i]
except IndexError:
sys.exit()
i += 1
[[email protected]_01 P36practise]#
運行結果:
[[email protected]_01 P36practise]# python 2-7.py
please input a string:
ahead blonging ok
a
h
e
a
d
b
l
o
n
g
i
n
g
o
k
**************************************************
網上搜來的方法:
a
h
e
a
d
b
l
o
n
g
i
n
g
o
k
野路子
a
h
e
a
d
b
l
o
n
g
i
n
g
o
k
修改程序後,禁止掉他的換行
[[email protected]_01 P36practise]# cat 2-7.py
#!/usr/bin/env python
#encoding:utf8
import sys
str = raw_input("please input a string:\n")
print
for i in str:
print i,
print
print
print "*"*50
print
print "網上搜來的方法:\n"
i = 0
while i < len(str):
if i == len(str):
print str[i]
else:
print str[i],
i += 1
print
print
print "野路子:\n"
i = 0
while str:
try:
print str[i],
except IndexError:
sys.exit()
i += 1
[[email protected]_01 P36practise]#
運行結果:
[[email protected]_01 P36practise]# python 2-7.py
please input a string:
what
w h a t
**************************************************
網上搜來的方法:
w h a t
野路子:
w h a t
[[email protected]_01 P36practise]#
2-8
[[email protected]_01 P36practise]# cat 2-8.py
#!/usr/bin/env python
#tuple1 = (1, 2, 3, 4, 5)
#list1 = [5, 6, 7, 8, 9]
#
def sum1(x):
sum = 0
for i in x:
sum += i
print sum,"sum1"
def sum2(x):
sum = 0
i = 0
list2 = list(x)
while i < len(list2):
sum += list2[i]
i += 1
print sum,‘sum2‘
#print "using for sum\n"
#sum1(tuple1)
#sum1(list1)
#print
#print "using while sum\n"
#sum2(list1)
#sum2(tuple1)
#
#print
#print "interactive input tuple or list:\n"
#
x = raw_input("please input a tuple or list:\n")
def f(x):
l = []
for i in x.split(‘ ‘):
try:
l.append(int(i))
except ValueError:
print ‘the value you input have some innumberal character\n‘
return l
y = f(x)
sum1(y)
運行結果
[[email protected]_01 P36practise]# python 2-8.py
please input a tuple or list:
1 2 3 4 5
15 sum1
2-9
[[email protected]_01 P36practise]# cat 2-9.py
#!/usr/bin/env python
#tuple1 = (1, 2, 3, 4, 5)
#list1 = [5, 6, 7, 8, 9]
#
def sum1(x):
sum = 0
for i in x:
sum += i
return sum
def sum2(x):
sum = 0
i = 0
list2 = list(x)
while i < len(list2):
sum += list2[i]
i += 1
return sum,list2
def average(x,y):
z = float(x) / y
print z
#print "using for sum\n"
#sum1(tuple1)
#sum1(list1)
#print
#print "using while sum\n"
#sum2(list1)
#sum2(tuple1)
#
#print
#print "interactive input tuple or list:\n"
#
x = raw_input("please input a tuple or list:\n")
def f(x):
l = []
for i in x.split(‘ ‘):
try:
l.append(int(i))
except ValueError:
print ‘the value you input have some innumberal character\n‘
return l
y = f(x)
average(sum1(y),len(y))
運行結果:
[[email protected]_01 P36practise]# python 2-9.py
please input a tuple or list:
1 2 3 4 5
3.0
2-10
代碼:
[[email protected]_01 P36practise]# cat 2-10.py
#!/usr/bin/env python
#encoding:utf
import sys
def num_judge(x):
if x >= 1 and x <= 100:
return True
else:
return False
while 1:
try:
x = int(raw_input(‘please input a num:\n‘))
except ValueError:
print "please input a number! byebye!\n"
sys.exit()
#一開始沒有對x進行int處理,導致在1~100之間的數字也不能成功
print ‘*‘*50
if num_judge(x):
print "success!"
print
else:
print ‘please input a number between 1 and 100‘
print
# else:
# x = raw_input(‘please input a num:\n‘)
# 一開始有這個部分,導致下面這種情況出錯:
# 先輸入一個不符合的數字,然後再輸入一個符合的,這是這個第一次符合的數字會誤判成不符合,就是因為多寫了這個else
# 後來把else:裏面加了pass。後來發現幹脆把else去掉了。i‘‘‘
#while 循環的核心思想是,只要為真,while中的子句總是從上往下一直執行下去
運行結果:
[[email protected]_01 P36practise]# python 2-10.py
please input a num:
1
**************************************************
success!
please input a num:
2
**************************************************
success!
please input a num:
101
**************************************************
please input a number between 1 and 100
please input a num:
adf
please input a number! byebye!
[[email protected]_01 P36practise]#
2-11
[[email protected]_01 P36practise]# cat 2-11.py
#!/usr/bin/env python
#encoding:utf8
import sys
#求和
def sum1(x):
sum = 0
for i in x:
sum += i
return sum
#求平均值
def average(x,y):
z = float(x) / y
print z
#轉換輸入的數據
def f(x):
l = []
for i in x.split(‘ ‘):
try:
l.append(int(i))
except ValueError:
print ‘the value you input have some innumberal character\n‘
return l
def max(x):
print "The maxium num in this line is :\n"
x = raw_input("please input a tuple or list:\n")
y = f(x)
print "please choose you calculator:\n"
print "(1)取五個數的和:\n(2)取五個數的平均值\n(X)退出\n"
while 1:
k = raw_input("please input a str in 1,2, ..., X:\n")
if k == ‘1‘:
print sum1(y)
if k == ‘2‘:
sum1(y)
print "*"*50
average(sum1(y),len(y))
if k == ‘3‘:
max(y)
if k == ‘X‘:
sys.exit()
運行結果:
[[email protected]_01 P36practise]# python 2-11.py
please input a tuple or list:
a 2 3 4 5
the value you input have some innumberal character
please choose you calculator:
(1)取五個數的和:
(2)取五個數的平均值
(X)退出
please input a str in 1,2, ..., X:
1
14
please input a str in 1,2, ..., X:
2
**************************************************
3.5
please input a str in 1,2, ..., X:
x
please input a str in 1,2, ..., X:
X
[[email protected]_01 P36practise]#
python核心編程第二版 第二章練習題解答 未完待續