ファイルの名前を尋ね、ファイルを開き、ファイル内の最大値と最小値を決定し、ファイル内の数値の平均も計算するプログラムを作成しようとしています。最大値と最小値を出力し、ファイル内の値の平均数を返したいと思います。このファイルには、1 行に 1 つの数字しかなく、上から下までさまざまな数字で構成されています。これまでの私のプログラムは次のとおりです。
def summaryStats():
fileName = input("Enter the file name: ") #asking user for input of file
file = open(fileName)
highest = 1001
lowest = 0
sum = 0
for element in file:
if element.strip() > (lowest):
lowest = element
if element.strip() < (highest):
highest = element
sum += element
average = sum/(len(file))
print("the maximum number is ") + str(highest) + " ,and the minimum is " + str(lowest)
file.close()
return average
プログラムを実行すると、次のエラーが表示されます。
summaryStats()
Enter the file name: myFile.txt
Traceback (most recent call last):
File "/Applications/Wing101.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 1, in <module>
# Used internally for debug sandbox under external interpreter
File "/Applications/Wing101.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 8, in summaryStats
builtins.TypeError: unorderable types: str() > int()
どの部分を弦にしようか悩んでいると思います。皆さんはどう思いますか?