2017-03-19 1 views
0

내가하려는 것은 사용자 입력을 기반으로 이름과 등급 목록을 작성한 다음 목록을 표시하고 테이블에 목록을 구성하는 것입니다 마지막으로 평균 점수를 계산합니다.Python 3.6에서 함수와리스트를 사용하여 평균 등급 계산하기

그래서 사용자에게 이름과 성적을 입력하고 목록에 저장하라는 내용의 스크립트를 원합니다. 이 프롬프트는 사용자가 빈 문자열을 입력 할 때까지 반복됩니다 (이름을 입력하라는 메시지가 나타나면 Enter 키를 누릅니다).

목록을 저장하는 중 문제가 발생하여 빈 문자열을 입력하면 인쇄 및 계산이 시작됩니다. 나는 인쇄 및 계산을 시작하려고 할 때 내 첫 번째 함수에 '없음'을 반환하지 않기 때문에

# Importing Python tabulate package 
from tabulate import tabulate 

# Defining functions 
def getRec(): 
    # Get a record from user input, return an empty of the user entered an empty string as input 
    name = str(input("Enter a name: ")) 
    if name != "": 
     score = int(input("Enter the grade of " + name +": ")) 
     return name,score 
    else: 
     return None 

def addList(List,rec): 
    # Add a rec into the list 
    List = tuple(rec) 
    return List,rec 

def putRec(List): 
    # Print a record in a specific format 
    print(List) 

def printTable(List): 
    # Print a table with a heading 
    print(tabulate(List,showindex="always",headers=["Index","Name","Grade"])) 

def average(List): 
    # Computes the average score and return the value 
    total = List[0][1] 
    avg = total/len(List) 
    print("Average Grade: ",avg) 

# Main function 

List = [] 
rec = [] 
while True: 
    rec = list(getRec()) 
    List = addList(List,rec) 

    if rec == None: 
     for index in range(len(List)): 
      print() 
      putRec(List) 
      print() 
      printTable(List) 
      print() 
      average(List) 
     break 

이 오류가있다 : 여기

는 내가 지금까지 무엇을 가지고 있습니다. 하지만 제가 0을 돌려 주면 목록은 0이됩니다. 다른 기능을 시작하고 입력을 기반으로 목록을 만드는 방법을 수정하는 데 도움이 필요합니다.

도움을 주시면 감사하겠습니다. 미리 감사드립니다.

답변

0

당신은 목록에 레코드를 추가하기 전에 여부 getRec() 반환 없음을 확인하지해야합니다

# Main function 

List = [] 
rec = [] 
while True: 
    result = getRec() 
    print(result) 

    if result == None: 
     for index in range(len(List)): 
      print() 
      putRec(List) 
      print() 
      printTable(List) 
      print() 
      average(List) 
     break 

    else: 
     rec = list(result) 
     addList(List,rec) 

또한 addList 기능에 실수가 있었다. 목록에 항목을 추가하려면 .append() 메서드를 사용해야합니다. 반환 값이 필요하지 않습니다.

def addList(List,rec): 
    # Add a rec into the list 
    List.append(tuple(rec)) 

코드는이 두 가지 변경 사항에 문제없이 실행해야하지만 평균 등급은 여전히 ​​틀립니다. 당신은 모든 등급의 합을 계산하는 루프를 사용할 필요가 :

def average(List): 
    # Computes the average score and return the value 
    total = 0 

    for r in List: 
     total += r[1] 

    avg = total/len(List) 
    print("Average Grade: ",avg) 

는 희망이 도움 :)

편집 :

당신은 전체 테이블을 인쇄하는 루프를 사용하는 이유는 확실하지. 당신은 단지 그것을 필요로하지 않습니다. 다음은 루프가없는 코드입니다.

while True: 
    result = getRec() 
    print(result) 

    if result == None: 
     print() 
     putRec(List) 
     print() 
     printTable(List) 
     print() 
     average(List) 
     break 

    else: 
     rec = list(result) 
     addList(List,rec) 
+0

코드가 작동합니다! 도와 주셔서 정말 감사합니다. 그러나 코드는 목록, 테이블 및 평균을 두 번 인쇄합니다. –

+0

내 대답을 편집했습니다.) –

+0

네 말이 맞아! for-loop를 사용하여 목록의 요소 수만큼 모든 것을 인쇄합니다. 밖으로 찾아 주셔서 감사합니다. –