亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在這個Python家庭作業問題上遇到麻煩

在這個Python家庭作業問題上遇到麻煩

BIG陽 2022-08-25 14:03:39
問題:編寫一個程序,以連續詢問用戶以整數百分比形式給出的考試分數,范圍為 0 到 100。如果輸入的值不在 -1 之外的范圍中,請打印出錯誤并提示用戶重試。計算輸入的所有有效等級的平均值以及每個字母等級類別中的等級總數,如下所示:90 至 100 表示 A,80 到 89 表示 B,70 到 79 表示 C,60 到 69 是 D,0 到 59 表示 F。(負值僅用于結束循環,因此不要在計算中使用它。例如,如果輸入是。#Enter in the 4 exam scoresg1=int(input("Enter an exam score between 0 and 100 or -1 to end: "))g2=int(input("Enter an exam score between 0 and 100 or -1 to end: "))g3=int(input("Enter an exam score between 0 and 100 or -1 to end: "))g4=int(input("Enter an exam score between 0 and 100 or -1 to end: "))total =(g1 + g2 + g3 + g4)while g1 is range(0,100):    continueelse:    print("Sorry",g1,"is not in the range of 0 and 100 or -1. Try again!")while g2 is range(0,100):    continueelse:    print("Sorry",g2,"is not in the range of 0 and 100 or -1. Try again!")while g3 is range(0,100):    continueelse:    print("Sorry",g3,"is not in the range of 0 and 100 or -1. Try again!")while g4 is range(0,100):    continueelse:    print("Sorry",g4,"is not in the range of 0 and 100 or -1. Try again!")#calculating Averagedef calc_average(total):    return total/4def determine_letter_grade(grade):    if 90 <= grade <= 100:        1 + TotalA    elif 80 <= grade <= 89:        1 + TotalB    elif 70 <= grade <= 79:        1 + TotalC    elif 60 <= grade <= 69:        1 + TotalD    else:        1 + TotalFgrade=totalaverage=calc_average#printing the average of the 4 scoresprint("You entered four valid exam scores with an average of: " + str(average))print("------------------------------------------------------------------------")print("Grade Distribution:")print("Number of A's: ",TotalA)print("Number of B's: ",TotalB)print("Number of C's: ",TotalC)print("Number of D's: ",TotalD)print("Number of F's: ",TotalF)
查看完整描述

4 回答

?
繁花如伊

TA貢獻2012條經驗 獲得超12個贊

在這里,您的問題可以分為幾個部分,

  1. 從用戶處獲取考試次數

  2. 從用戶獲取這些考試的有效輸入

  3. 計算所有考試的平均值

  4. 計算等級分布

  5. 如果用戶輸入為 -1,則退出

下面的代碼遵循所有這些步驟

 #calculating Average

    def calc_average(scores):

            return sum(scores)/len(scores)




    grade_dist = {

    (90, 101):'A',

    (80,90):'B',

    (70, 80):'C',

    (59, 70):'D',

    (0,59):'F'

    }


    def get_grade_freq(scores):

        grades = {'A':0, 'B':0, 'C':0, 'D':0, 'F':0}


        for score in scores:

          for k, v in grade_dist.items():

            if score in range(k[0], k[1]):

              grades[v]+=1


        print("Grade distributions")


        for grade, number in grades.items():

            print("Number of {}’s = {}".format(grade, number))




    def get_scores(n):

        scores = []

        cond = True

        while cond and n>0:

          score = int(input("Enter an exam score between 0 and 100 or -1 to end : "))

          if score==-1:

            cond=False

            return -1

          if score not in range(0,101):

              print("Sorry, {} is not in the range of 0 and 100 or -1. Try Again!".format(score))

          if score in range(0,101):

            scores.append(score)

            n-=1

        return scores


    def main():

        n = int(input('total number of exams ' ))


        scores = get_scores(n)

        if scores == -1:

            exit(-1)


        average = calc_average(scores)


        print("You entered {} valid exam scores with an average of {}.".format(n, average))


        get_grade_freq(scores)



    if __name__=='__main__':

        main()


查看完整回答
反對 回復 2022-08-25
?
catspeake

TA貢獻1111條經驗 獲得超0個贊

每當有多個類似事物的實例需要操作(評分范圍、總數)時,都必須嘗試使用多值結構,而不是單個變量。Python的列表和字典旨在收集多個條目作為位置列表或鍵控索引(字典)。


這將使您的代碼更加通用。當您操作概念而不是實例時,您將知道自己走在正確的軌道上。


例如:


grading = [(None,101),("A",90),("B",80),("C",70),("D",60),("F",0)]

scores  = {"A":0, "B":0, "C":0, "D":0, "F":0}

counts  = {"A":0, "B":0, "C":0, "D":0, "F":0}

while True:

    input_value = input("Enter an exam score between 0 and 100 or -1 to end: ")

    value       = int(input_value)

    if value == -1: break

    score = next((s for s,g  in grading if value >= g),None)

    if score is None:

        print("sorry ",input_value," is not -1 or in range of 0...100")

        continue

    scores[score] += value

    counts[score] += 1


inputCount = sum(counts.values())

average    = sum(scores.values())//max(1,inputCount)  

print("")

print("You entered", inputCount, "valid exam scores with an average of: ", average)

print("------------------------------------------------------------------------")

print("Grade Distribution:")

for grade,total in counts.items():

    print(f"Number of {grade}'s: ",total)

該列表包含分數字母和最小值(以元組為單位)對。這樣的結構將允許您通過查找值低于或等于輸入值的第一個條目并使用相應的字母,將中的成績值轉換為評分字母。grading


同一列表用于驗證輸入值,方法是有策略地將 None 值放在 100 之后,并且不低于零的值。該函數將為您執行搜索,并在不存在有效條目時返回 None。next()


您的主程序循環需要繼續,直到輸入值為 -1,但它需要至少通過輸入一次(典型的重復-直到結構,但在 Python 中只有一個)。因此,該語句將永遠循環(即在 True 時),并且在滿足退出條件時需要任意中斷。whilewhile


為了累積分數,字典 () 比列表更適合,因為字典將允許您使用鍵(分數字母)訪問實例。這允許您跟蹤單個變量中的多個分數。計算每個分數的輸入數量也是如此。scores


要獲得最后的平均值,您只需將字典的值分數相加,然后除以添加到字典中的分數計數即可。scorescounts


最后,要打印分數計數的摘要,您可以再次利用字典結構,并且只為所有分數字母和總計編寫一個廣義的打印行。


查看完整回答
反對 回復 2022-08-25
?
藍山帝景

TA貢獻1843條經驗 獲得超7個贊

以下是我的演練解釋:


因此,該程序應該詢問用戶他們得到了什么分數,直到他們說他們得到了一個分數,在你給他們結果之后。要循環直到它們給出,我們可以使用一個循環:-1-1while


inp = float(input("Enter an exam score between 0 and 100 or -1 to end: ")) # Get input

grades = []

while inp > -1: # Loop until user gives a score of -1

    if inp >= 0 and inp <= 100: # Check if valid grade

        grades.append(inp) # Add grade to grades list

        inp = float(input("Enter an exam score between 0 and 100 or -1 to end: ")) # Ask again

    else:

        print("Sorry", inp, "is not in the range of 0 and 100 or -1. Try again!") # Invalid grade


# ANALYSIS OF GRADES


# Format first line of output - the first str(len(grades)) give the amount of grades they entered,

# and the str(sum(grades) / len(grades)) gives the average of the grades list.

print("You entered", str(len(grades)), "valid exam scores with an average of", str(sum(grades) / len(grades)))


print("Grade Distribution:")

print("Number of A's =", str(sum(90 <= g <= 100 for g in grades)) # I am using a very short notation

print("Number of B's =", str(sum(80 <= g <= 89 for g in grades)) # here - this is basically counting

print("Number of C's =", str(sum(70 <= g <= 79 for g in grades)) # the number of grades that are

print("Number of D's =", str(sum(60 <= g <= 69 for g in grades)) # a valid value based on the checks

print("Number of F's =", str(sum(0 <= g <= 59 for g in grades)) # I am making.

希望我的評論能幫助你弄清楚我的代碼中發生了什么!


查看完整回答
反對 回復 2022-08-25
?
天涯盡頭無女友

TA貢獻1831條經驗 獲得超9個贊

這可能適用于您:


scores = {

    "A": 0,

    "B": 0,

    "C": 0,

    "D": 0,

    "F": 0,

}

total = 0

count = 0


input_value = 0


while (input_value != -1) and (count < 4):

    input_value = int(input("Enter an exam score between 0 and 100 or -1 to end: "))

    if 0 <= input_value <= 100:

        total += input_value

        count += 1

        if input_value >= 90:

            scores["A"] += 1

        elif input_value >= 80:

            scores["B"] += 1

        elif input_value >= 70:

            scores["C"] += 1

        elif input_value >= 60:

            scores["D"] += 1

        else:

            scores["F"] += 1

    else:

        print("Sorry", input_value, "is not in the range of 0 and 100 or -1. Try again!")


print("You entered {} valid exam scores with an average of: {}".format(count, total / count))

print("------------------------------------------------------------------------")

print("Grade Distribution:")

print("Number of A's: ", scores['A'])

print("Number of B's: ", scores['B'])

print("Number of C's: ", scores['C'])

print("Number of D's: ", scores['D'])

print("Number of F's: ", scores['F'])


查看完整回答
反對 回復 2022-08-25
  • 4 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號