[英]Easy python program
提示用戶輸入文件,在這種情況下為“ histogram.txt”。 該程序將獲取文本文件中的每個分數,並從文件中的所有成績中做出直方圖,並對它們進行組織,以便用戶可以看到每個范圍中有多少個分數。 我寫了一個非常簡單的代碼:
filename = raw_input('Enter filename of grades: ')
histogram10 = 0
histogram9 = 0
histogram8 = 0
histogram7 = 0
histogram6 = 0
histogram5 = 0
histogram4 = 0
histogram3 = 0
histogram2 = 0
histogram1 = 0
histogram0 = 0
for score in open(filename):
if score >= 100:
histogram10 = histogram10 + 1
elif score >= 90:
histogram9 = histogram9 + 1
elif score >= 80:
histogram8 = histogram8 + 1
elif score >= 70:
histogram7 = histogram7 + 1
elif score >= 60:
histogram6 = histogram6 + 1
elif score >= 50:
histogram5 = histogram5 + 1
elif score >= 40:
histogram4 = histogram4 + 1
elif score >= 30:
histogram3 = histogram3 + 1
elif score >= 20:
histogram2 = histogram2 + 1
elif score >= 10:
histogram1 = histogram1 + 1
elif score >= 0:
histogram0 = histogram0 + 1
print
print 'Grade Distribution'
print '------------------'
print '100 :',('*' * histogram10)
print '90 - 99 :',('*' * histogram9)
print '80 - 89 :',('*' * histogram8)
print '70 - 79 :',('*' * histogram7)
print '60 - 69 :',('*' * histogram6)
print '50 - 59 :',('*' * histogram5)
print '40 - 49 :',('*' * histogram4)
print '30 - 39 :',('*' * histogram3)
print '20 - 29 :',('*' * histogram2)
print '10 - 19 :',('*' * histogram1)
print '00 - 09 :',('*' * histogram0)
但是,每當我運行程序時,所有二十個成績都會記錄在> = 100上,如下所示:
100 : ********************
90-99 :
80-89 :
等等...如何使程序將星星放置在正確的位置?
從文件讀取的數據是字符串。 首先將其傳遞給int()
,將其轉換為整數。
>>> int('25')
25
比較之前,您需要將score
轉換為int。
score = int(score) # convert to int
if score >= 100:
histogram10 = histogram10 + 1
# other cases
如果輸入文件中有空行,則必須在轉換為int之前添加必要的檢查。 此外,您可以輕松使用列表來代替十個不同的變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.