簡體   English   中英

計算用戶輸入的隨機數的平均值(python)

[英]Calculate average of random amount of numbers entered by user (python)

我需要編寫一個代碼來計算用戶輸入的數字的平均值。 我該怎么做才能幫助它計算平均值。 我嘗試使用總和 function 和 Len,但后來它說了一些關於 int 和 str 不匹配的信息。 我只需要一個提示。 基本上,代碼要求用戶輸入學生姓名,然后你輸入它,然后提示你輸入他們在主題 1、2、3 的分數。完成后,它會詢問你是否還有更多學生左。 如果你說是,它會為你重播代碼,如果你說不是,它會停止循環並首先計算主題 1 的平均值,然后是主題 2,然后是主題 3。(我只需要幫助,而不是整個代碼)

while True: 
    name = str(input("Enter student name: ")) 
    print()
    Topic1 = int(input("Enter student score for topic 1: "))
    Topic2 = int(input("Enter student score for topic 2: "))
    Topic3 = int(input("Enter student score for topic 3: "))
    #calculate average of scores inputted by user for topic one, two, three.
    
    Continue = str(input("Would you like to add more students? "))
    if Continue == 'yes':
            continue
    elif Continue == 'no':
        break 

如果我正確理解了您的問題,則每次用戶提供新學生的信息時,您都希望將 append 的分數分隔為主題 1、2 和 3 分數的列表。 您可以通過將其總和除以其長度來計算整數列表的平均值。 我有點困惑為什么即使用戶輸入“是”你也會在最后break ,但我會把這部分留給你去解決。

topic1_scores = []
topic2_scores = []
topic3_scores = []

while True: 
    name = str(input("Enter student name: "))
    print()
    topic1_scores.append(int(input("Enter student score for topic 1: ")))
    topic2_scores.append(int(input("Enter student score for topic 2: ")))
    topic3_scores.append(int(input("Enter student score for topic 3: ")))

    topic1_average = sum(topic1_scores) / len(topic1_scores)
    topic2_average = sum(topic2_scores) / len(topic2_scores)
    topic3_average = sum(topic3_scores) / len(topic3_scores)
    #calculate average of scores inputted by user for topic one, two, three.
    
    Continue = str(input("Would you like to add more students? "))
    if Continue == 'yes':
            break   # why???
    elif Continue == 'no':
        break 

我不知道為什么你在 if 和 elif 中添加 break,如果它是或否,並且在 if 塊中,縮進不正確。

if Continue == 'yes':
        break #in here
elif Continue == 'no':
    break 

我寫了一些簡單的代碼,你可以詢問主題的數量並詢問每個金額並獲得它們的平均值以鎖定它。

subjects = int(input('Enter number of subjects: '))
scores = []
for sub in range(0, subjects):
    sub_score = int(input(f'Enter subject {sub + 1} score: '))
    scores.append(sub_score)

avarage_score = sum(scores) / subjects
print(avarage_score)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM