簡體   English   中英

我的子程序中不斷出現無限循環,有人可以幫助我嗎?

[英]I keep getting infinite loops in my subroutines, can someone help me?

我正在嘗試使用子例程和文本文件來記錄和輸出學生數據,但我有選項 1,2 和 4 的無限循環,並且不知道如何修復它我的代碼:

def displayMenu():
    print("1. save to new file")
    print("2. append to and existing file")
    print("3. calculate the average mark")
    print("4. display data")
    choice = input("enter choice")
    while int(choice) <1 or int(choice) >5:
        choice = input("pick a valid option")
    return choice
def saveToFile(a):
    studentMark = "0"
    studentName = input("enter a student name, type xxx when you are done")
    while studentName != "xxx":
        file = open ("studentMark.txt", "w")
        f = open("studentNames.txt", "w")

        studentMark = input("Enter mark:")
        f.write(studentName +"\n")
        file.write(studentMark + "\n")
        studentName = input("name")
        f.close()
        file.close()

def appendToFile(b):
    studentMark = "0"
    studentName = input("enter a student name, type xxx when you are done")
    while studentName != "xxx":
        file = open ("studentMark.txt", "a")
        f = open("studentNames.txt", "a")

        studentMark = input("Enter mark:")
        f.write(studentName +"\n")
        file.write(studentMark +"\n")
        studentName = input("name")
        f.close()
        file.close()
def average(c):
    total = 0.0
    length = 0.0
    average = 0.0
    file2 = open("studentMark.txt", "r")
    for line in file2:

        amount = float(studentmark)
        total += amount
        length = length + 1
    average = total / length
    print("Average mark:", average)
    file2.close()
def printstuff(d):
    o = open('output.txt', 'w')

    fh = open("studentNames.txt", "r")
    fh2 = open("studentMark.txt", "r")

    for line in (fh.readlines()):
        o.write(line.strip("\r\n") + "\t" + fh2.readline().strip("\r\n") + "\n")
    o.close()
    o = open("output.txt", "r")
    output = o.read()
    print(output)

    fh.close()
    fh2.close()
    o.close()

option = displayMenu()
while option != "5":
    if option == "1":
        saveToFile("write")
    elif option == "2":
        appendToFile("append")
    elif option == "3":
        average("mark")
    elif option == "4":
        printstuff("display")

print("quit")

我的代碼的計算平均值部分是從論壇復制和編輯的,因此可能存在一些過時的代碼和內容

我通過不允許用戶更改他們的選項來創建一個無限循環

暫無
暫無

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

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