《Python核心编程》第二版第36页第二章练习 续一 -Python核心编程答案-自己做的-...
2-6.
條件判斷。判斷一個數是正數還是負數,或者是0。開始先用固定的數值,然后修改你的代碼支持用戶輸入數值再進行判斷。
【答案】
代碼如下:
a = float(raw_input("Please input a number ... "))
if a == 0:
??? print "The number you input is Zero"
elif a > 0:
??? print "The number you input is Positive"
else:
??? print "This is a negative number"
2-7.
循環和字串。從用戶那里接受一個字符串輸入,然后逐字符顯示該字符串。先用while循環實現,然后再用for循環實現。
【答案】
代碼如下:
a = raw_input("Please input a string ... ")
print 'Display in for loop:'
for i in a:
??? print i,
print '\nDisplay in while loop:'
j = 0
while (j < len(a)):
??? print a[j]
??? j = j + 1
2-8.
循環和操作符。創建一個包含五個固定數值的列表或元組,輸出他們的和。然后修改你的代碼為接受用戶輸入數值。分別使用while和for循環實現。
【答案】
代碼如下:
# Using while loop
i = 0
total = 0
a = [1, 2, 3, 4, 5]
while (i < 5):
??? print 'Please input number', i+1
??? a[i] = float(raw_input())
??? total = total + a[i]
??? i = i + 1
print 'The total is', total
# Using for loop
total = 0
a = [1, 2, 3, 4, 5]
for i in range(0, 5):
??? print 'Please input number', i+1
??? a[i] = float(raw_input())
??? total = total + a[i]
print 'The total is', total
2-9.
循環和操作符。創建一個包含五個固定數值的列表或元組,輸出他們的平均值。本練習的難點之一是通過除法得到平均值。你會發現整型除會截去小數,因此你必須使用浮點除以得到更精確的結果。float()內建函數可以幫助你實現這一功能。
【答案】
代碼如下:
i = 0
total = 0
a = [1, 2, 3, 4, 5]
while (i < 5):
??? print 'Please input number', i+1
??? a[i] = float(raw_input())
??? total = total + a[i]
??? i = i + 1
print 'The average is', total / 5.
# Using for loop
total = 0
a = [1, 2, 3, 4, 5]
for i in range(0, 5):
??? print 'Please input number', i+1
??? a[i] = float(raw_input())
??? total = total + a[i]
print 'The average is', total / 5.
2-10.
帶循環和條件判斷的用戶輸入。使用raw_input()函數來提示用戶輸入一個1和100之間的數,如果用戶輸入的數值滿足這個條件,顯示成功并退出。否則顯示一個錯誤信息然后再次提示用戶輸入數值,直到滿足條件為止。
【答案】
代碼如下:
t = 1
while (t):
??? a = float(raw_input('Please input a number between 1 and 100: ... '))
??? if a < 100 and a > 1:
??????? print 'Your have input a number between 1 and 100.'
??????? t = 0
??? else:
??????? print 'Please try again ...'
【未完】這里并沒有檢查輸入不是數字的情況。
這里列出的答案不是來自官方資源,是我自己做的練習,可能有誤。
轉載于:https://www.cnblogs.com/balian/archive/2011/01/12/1933418.html
總結
以上是生活随笔為你收集整理的《Python核心编程》第二版第36页第二章练习 续一 -Python核心编程答案-自己做的-...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 云计算背后的秘密(6)-NoSQL数据库
- 下一篇: 常用扩展之枚举扩展