如何在Python中重复代码块

时间:2015-10-31 16:02:56

标签: python

我创建了一个代码,允许用户查看文件中值的平均分数。在示例中,文本文件如下所示:

Class 1的文本文件: 每个文本文件都类似; 2和3.只是不同的名称和值

$(function () { 
  $(document).on("keyup", function (e) {
    if (e.keyCode == 32) {
        $(".slide.active > img").toggleClass('background_cover'); 
    }
  });
});

共有3个类,系统会提示用户选择要预览的类。

代码:

Matt 2
Sid 4
Jhon 3
Harry 6

问题 如果我想保持重复上面的代码,以便用户可以继续使用它,直到他们想要退出。所以,是否可以将代码放入while循环中,并且只在用户想要时停止代码,即如果用户想要选择其他选项和类,则会提示用户。 注意:还会有其他选项,例如字母顺序,但是现在我只想知道如何为平均部分做这个。

3 个答案:

答案 0 :(得分:1)

您可以做的最好的事情是为用户输入创建循环并编写用于列出文件的函数。

def main_menu():
    print ("\n         Main Menu        ")
    print ("1.Average Score of class = 'avg'")

main_menu()

option = ""
options = ["1", "2", "3"]

one = "1.txt"
two = "2.txt"
three = "3.txt"

def read_text_file(file): # standalone function for viewing files to reduce duplicate code
    file += ".txt"
    with open(file) as f:
            the_list = [int(l.strip().split()[-1]) for l in f]

            b = sum(the_list)
            length = len(the_list)
            avg = float(b) / length if length else 0
            print ("Average of Class is: ", avg)

while True:

    option = input("option [avg]: ").lower()
    if option == "exit":
        break # checks if user want to exit a program
    else:
        option_class = input("class: ")

        if option == 'avg' and option_class in options:
            read_text_file(option_class)

        else:
            print("nothing to show, asking again")

print("end of program")

答案 1 :(得分:0)

是的,您可以将代码置于while循环中并提示用户输入:

def main_menu():
        print ("\n         Main Menu        ")
        print ("1.Average Score of class = 'avg'")
# End main_menu()

one = "1.txt"
two = "2.txt"
three = "3.txt"

keepGoing = True
while(keepGoing):
        main_menu()

        option = input("option [avg]: ")
        option_class = input("class: ")
        if option.lower() == 'avg' and option_class == '1':
            with open(one) as f:
                the_list = [int(l.strip().split()[-1]) for l in f]

                b = sum(the_list)
                length = len(the_list)
                avg = float(b) / length if length else 0
                print ("Average of Class is: ", avg)

        if option.lower() == 'avg' and option_class == '2':
            with open(two) as f:
                the_list = [int(l.strip().split()[-1]) for l in f]

                b = sum(the_list)
                length = len(the_list)
                avg = float(b) / length if length else 0
                print ("Average of Class is: ", avg)

        if option.lower() == 'avg' and option_class == '3':
            with open(three) as f:
                the_list = [int(l.strip().split()[-1]) for l in f]

                b = sum(the_list)
                length = len(the_list)
                avg = float(b) / length if length else 0
                print ("Average of Class is: ", avg)

        # Prompt user for input on whether they want to continue or not:

        while(True):
                keepGoingStr = input("Would you like to continue? (Y/N)\n>>> ").lower()
                if(keepGoingStr[0] == 'y'):
                        # Keep going
                        keepGoing = True
                        break
                elif(keepGoingStr[0] == 'n')
                        # Stop
                        keepGoing = False
                        break
                else:
                        print("Sorry, your input did not make sense.\nPlease enter either Y or N for yes or no.")
                # end if
        # end while - keep going input

# End While(keepGoing)

如评论中所述,您应该考虑将代码分解为函数。

答案 2 :(得分:0)

正如我在评论部分所提到的,你应该利用这里的功能。通过将组件分解为可管理的组件,您实际上可以提供可读性和灵活性。请参阅下面的代码,其中我有两个函数,一个用于平均值,一个用于总计。

def get_class_average(class_number):

    filename = "{0}.txt".format(class_number)
    try:
        with open(filename) as f:
            the_list = [int(l.strip().split()[-1]) for l in f]
            b = sum(the_list)
            length = len(the_list)
            avg = float(b) / length if length else 0
            return avg
    except:
        print "No file with that name found."


def get_class_total(class_number):

    filename = "{0}.txt".format(class_number)
    try:
        with open(filename) as f:
            the_list = [int(l.strip().split()[-1]) for l in f]
            b = sum(the_list)
            return b
    except:
        print "No file with that name found."


def check_class_number(string_input):

    try:
        int(string_input)
        return True
    except ValueError:
        return False

if __name__ == "__main__":

    while True:

        input_val = raw_input(
            "Enter class number (enter 'exit' to quit program): ")
        if input_val == 'exit':
            break

        if check_class_number(input_val):  # If it's a valid class number.
            method = raw_input("Enter method: ")
            if method == 'avg':
                avg = get_class_average(int(input_val))
                print "The average of Class {0} is {1}".format(input_val, avg)
            elif method == 'sum':
                total = get_class_total(int(input_val))
                print "The total of Class {0} is {1}".format(input_val, total)
        else:
            print "That is not a valid class number."
            continue

示例运行:

enter image description here

这里真正有趣的部分是,您甚至可以将get_class_averageget_class_total重构为单个函数,以检查传入的method是否为{ {1}}或avg并从那里返回相应的值(这很容易实现,因为两个函数实际上都有相同的代码行,sum只涉及额外的除法。)

玩得开心。