我不得不採取從文本文件信息的格式的文件得到的平均值:如何我可以從保存爲文本文件
Dom : 9
Eathan : 0
Harry : 8
Jack : 7
Jake : 0
James : 1
Jeffin : 1
Louis : 8
Sam : 0
Tom : 3
William : 0
我需要從這個文本文件中把分數保存作爲int
(因爲它們是字符串)並計算出平均值並打印出來。
import random
import operator
def randomCalc():
ops = {'+':operator.add,
'-':operator.sub,
'*':operator.mul,
'/':operator.truediv}
num1 = random.randint(0,12)
num2 = random.randint(1,10)
op = random.choice(list(ops.keys()))
answer = ops.get(op)(num1,num2)
print('What is {} {} {}?\n'.format(num1, op, num2))
return answer
def askQuestion():
answer = randomCalc()
while True:
try:
guess = float(input())#The Answer the user inputs to the question asked
except ValueError: #When anything but a interger is inputted.
print ("That is not a valid answer")
continue #Dosen't print Invalid Code Error
else:
break
return guess == answer
def quiz():
print('Welcome. This is a 10 question math quiz\n')
score = 0
for i in range(10):
correct = askQuestion()
if correct:
score += 1
print('Correct!\n')
else:
print('Incorrect!\n')
print ("\nYour score was {}/10 Well done".format(score))
print ("\nWhat is your name")
name = str(input())
class_name = input("\nWhich class do you wish to input results for? ")
class_name = class_name + ".dat" #adds '.txt' to the end of the file so it can be used to create a file under the name a user specifies
file = open(class_name, "a") #opens the file in 'append' mode so you don't delete all the information
name = (name)
file.write(str(name + " : ")) #writes the information to the file
file.write(str(score))
file.write('\n')
file.close()
return score
quiz()
viewscore_alpha = str(input("\nWould you like to view the score`s of players alphabeticaly: Yes or No"))
if viewscore_alpha == "yes".lower():
class_name = input("\nWhich class do you wish to View results for? ")
class_name = class_name + ".dat"
with open(class_name) as file: # use with to open files as it closes them automatically
file.seek(0) # go back to start of file
for line in f: # print each name
print(line)
file.seek(0) # go back to start again
lines = sorted(file.readlines()) # sort the names
with open(class_name, "w") as file_save: # write names in sorted order
for line in lines:
file_save.write(line)
file.close()
file_save.close90
elif viewscore_average == "no".lower() :
viewscore_average = str(input("\nWould you like to view the score`s of classes avrages?: Yes or No"))
if viewscore_average == "yes".lower():
chars = set("")
else:
viewscore_higest = str(input("\nWould you like to view the score`s of players alphabeticaly: Yes or No"))
if viewscore_higest == "yes".lower():
這就是我所有的,我卡住了。
請張貼代碼的其餘部分因爲我們無法猜測你做了什麼。 – wheaties
是的,請張貼代碼。否則,它看起來像你要求我們爲你寫的代碼,這裏不允許使用。 此外,顯示您輸出*做*得到 - 至少一個阻塞語法錯誤。評論也將有所幫助,所以我們知道你設計了什麼(你正在努力做什麼)。 – Prune
一開始,你應該嘗試移動'低()'函數您的變量,例如'viewscore_average.lower()'。 –