有没有办法缩短这个?

时间:2016-11-24 06:13:35

标签: python

非常初学的程序员在这里学习。我只是想知道我输入的这个简单代码是否是最佳方式。

with open('guest_book.txt', 'a') as file_object:
    while True:
        name=input("What is your name?")
        print("Welcome " + name + ", have a nice day!")
        file_object.write(name + " has visited! \n")
        another = input("Do you need to add another name?(Y/N)")
        if another == "y":
            continue
        elif another == "n":
            break
        else:
            print("That was not a proper input!")
            while True:
                another = input("Do you need to add another name?(Y/N)")
                if another == "y":
                    a = "t"
                    break
                if another == "n":
                    a = "f"
                    break
            if a == "t":
                continue
            else:
                break

我的问题在if语句中。当我问输入(“你需要添加另一个名字吗?(y / n)”时,如果我得到除y或n以外的答案,我输入的最佳方法是重新提问。基本上我想要的如果我没有得到是或否的答案,那么问题就要重复了,我发现的解决方案似乎不是最优解决方案。

3 个答案:

答案 0 :(得分:2)

你基本上就在那里。你可以简单地说:

with open('guest_book.txt', 'a') as file_object:
    while True:
        name=input("What is your name?")
        print("Welcome " + name + ", have a nice day!")
        file_object.write(name + " has visited! \n")
        another = input("Do you need to add another name?(Y/N)")
        if another == "y":
            continue
        elif another == "n":
            break
        else:
            print("That was not a proper input!")
            continue

答案 1 :(得分:0)

您可以使用函数在一个地方编写所有逻辑。

def calculate(file_object):
    name=raw_input("What is your name?")
    print("Welcome " + name + ", have a nice day!")
    file_object.write(name + " has visited! \n")
    another = raw_input("Do you need to add another name?(Y/N)")
    if another == "y":
        calculate(file_object)
    elif another == "n":
        return
    else:
        print("That was not a proper input!")
        calculate(file_object)

if __name__=='__main__':    
    with open('guest_book.txt', 'a') as file_object:
        calculate(file_object)

答案 2 :(得分:0)

你可以这样做,但不会有任何无效的输入说不。它只会检查说y

with open('guest_book.txt', 'a') as file_object:
    another = 'y'
    while another.lower() == 'y':
        name=input("What is your name?")
        print("Welcome " + name + ", have a nice day!")
        another = input("Do you need to add another name?(Y/N)")