简单的python程序

2024-07-08 17:11:45 发布

您现在位置:Python中文网/ 问答频道 /正文

系统会提示用户输入一个文件,在本例中是'直方图.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)

但是,每当我运行程序时,所有20个等级都会被记录到>;=100 像这样:

^{pr2}$

等等。 ... 我怎样才能让程序把星星放在正确的位置?在


Tags: 程序scoreprintelifhistogram1histogram2histogram4histogram6
2条回答

从文件读取的数据是字符串。首先将其传递给int(),将其转换为整数。在

>>> int('25')
25

在比较之前,您需要将score转换为int。在

score = int(score)  # convert to int
if score >= 100:
    histogram10 = histogram10 + 1
# other cases

如果在输入文件中有空行,那么在转换为int之前必须添加必要的检查。另外,您可以轻松地使用一个列表来代替十个不同的变量。在

相关问题 更多 >

    热门问题