2017-02-25 50 views
-3

這個問題我來回答:我得到這個語法錯誤:類型錯誤:不支持的操作數類型(S)爲+:「詮釋」和「海峽」

編寫一個程序,輸入考試成績(滿分100),直到你輸入'quit'。完成輸入考試分數後,該程序將打印出所有考試分數的平均值。

提示: 要計算出平均值,您必須保持考試分數的總計和輸入的數字的計數。 嘗試使程序工作1次,然後找出退出條件並使用一段時間True:循環。

示例執行: 輸入考試的分數或類型「退出」:100 輸入考試的分數或類型「退出」:100 輸入考試的分數或類型「退出」:50 輸入考試的分數或類型「退出」:退出 分數數3.平均爲83.33

這是我的代碼:

count = 0 
average = sum 
while True: 
    num =input('Enter an exam score or type "quit":') 
    count = count + 1 
    average = sum(num) 
    print ('the total of exams is %d and the average is %f' % count, average) 
    if num == 'quit': 
     break 
print ('this is ok for now') 
+0

您首先需要'int'(..)'num'。 –

+0

謝謝,但這是我得到的:TypeError:'int'對象是不可迭代的 –

+0

但是你輸入的元素一個接一個。所以你應該使用一個每次增加'num'的運行變量...... –

回答

0

這一行有很多問題:average = sum(num)

sum的適當輸入是要求和的數字列表。在你的情況下,你有一個單一的數字或單詞「退出」。

你需要做的是跟蹤計數和運行總的,然後做你的師結尾:

total = 0 
count = 0 
while True: 
    # With raw_input, we know we are getting a string instead of 
    # having Python automatically try to interpret the value as the 
    # correct type 
    num = raw_input('Enter an exam score or type "quit":') 
    if num == "quit": 
     break 
    # Convert num from a string to an integer and add it to total 
    total += int(num) 
    count = count + 1 
average = total/count 
print("The total number of exams is {} and the average is {}".format(count, average)) 
0

我採取的將使用statistics模塊和sys用於退出。還處理非int(或非float)輸入並打印正確的消息,而不是使用ValueError退出

import statistics, sys 

notes = [] 
count = 0 
average = 0 # or None 
while True: 
    note = input('Enter score: ') 
    # handle quit request first, skip any calculation 
    # if quit is the first request 
    if note == 'quit': 
     print('Program exit. Average is %s' % average) 
     sys.exit() 
    else: 
     # test if the entered data can be an int or float 
     try: 
      note = int(note)  # can be replaced with float(note) if needed 
      count += 1   # increase the counter 
      notes.append(int(note)) 
      average = statistics.mean(notes) # calculate the average (mean) 
      print('Total %s average is %s' % (count, average)) 
     # just print an error message otherwise and continue 
     except ValueError: 
      print('Please enter a valid note or "quit"') 
相關問題