使用While或For循环重复代码块

时间:2015-05-05 19:24:59

标签: python loops

以下是我需要使用python v3.4重复im的所有代码块

    x = input ("Username: ")
    if x == "reed":
        f1 = input ("password: ")
        if f1 == "reed1":
            m = input ("hello reed how may i assist you today: Settings, File Directory: ")
            if m == "Settings":
                print ("Loading Settings")
                m3 = input ("Internet, Update, Sound: ")
                if m3 == "Internet":
                    n3 = input (": ")
                elif m3 == "Update":
                    n7 = input (": ")
                elif m3 == "Sound":
                    n8 = input (": ")
           elif m == "File Directory":
               print ("Loading File Directory")
               m2 = input ("C:, D:, Program Files: ")
               if m2 == "C:":
                   input ("type file name.ext: ")
               elif m2 == "D:":
                   m3 = input ("type file name.ext: ")
           if m3 == "poem":
                poem_1 = open ("C:\Python34\poems\The Friend.txt")
                print(poem_1.read(500000))
                poem_1.close()
           elif m2 == "Program Files":
                ba = input ("type file name.ext: ")
else:
    print ("incorrect password continuing program")

我需要的是重复这段代码,否则while语句没用,它只重复第一行,我不能使用for语句。现在我只是打字浪费空间所以它会让我发布

1 个答案:

答案 0 :(得分:3)

将功能分解为函数确实有助于清理代码。我建议您为变量提供有意义的名称(例如user而不是x)。

我已经删除了一些代码,这些代码并不是为了让您了解一种可以实现的方式。可能有很多其他(更好的)方法可以解决这个问题。

我开始时定义了一些函数来处理文件顶部的重复任务。

def Login():
    user = input("Username: ")
    password = input("password: ")
    return user == "reed" and password == "reed1"

def DoSettings():
    print("Loading Settings")
    subcommand = input("Internet, Update, Sound: ")
    if subcommand == "Internet":
        print("Internet is broken!")
    elif subcommand == "Update":
        print("Ambiguous update... updating all the things!!!")
    elif subcommand == "Sound":
        print("Beep beep!")

def DoFileDirectory():
    print("Doing file stuff")

然后我用程序的主循环跟进了这个。我假设你只需要登录一次,这样就不在循环之内了。之后,它会循环,直到您输入Quit

if not Login():
    print("Hey! You're not reed!")
    exit()

MAIN_PROMPT = "Hi reed, how may I assist you today? Settings, File Directory, Quit: "
command = input(MAIN_PROMPT)
while not command == "Quit":
    if command == "Settings":
        DoSettings()
    elif command == "File Directory":
        DoFileDirectory()
    else:
        print("Unrecognized command")
    command = input(MAIN_PROMPT)

print("Goodbye!~")