按下Enter键时断开循环

时间:2016-06-20 19:31:52

标签: python loops

我在按下Enter时试图打破循环,同时将数据写入文件。这就是我到目前为止所拥有的。我也不想限制循环运行的时间...(示例输出在下面)

def main():
    myfile = open('friends.txt','w')
    friend = input('Enter first name of friend or Enter to quit')
    age = input('Enter age (integer) of this friend')

while friend != '':

    for n in range():
        friend = input('Enter first name of friend or Enter to quit')
        age = input('Enter age (integer) of this friend')

        myfile.write(friend +'\n')
        myfile.write(str(age) +'\n')

    myfile.close()
main()

这就是当它正确运行时输出的方式。

Enter first name of friend or Enter to quit Sally
Enter age (integer) of this friend 20
Enter first name of friend or Enter to quit Sam
Enter age (integer) of this friend 24
Enter first name of friend or Enter to quit 
File was created

2 个答案:

答案 0 :(得分:1)

def main():
    myfile = open('friends.txt','w')

    while True:
        friend = input('Enter first name of friend or Enter to quit: ')
        if not friend:
            myfile.close()
            break
        else:
            age = input('Enter age (integer) of this friend: ')
            myfile.write(friend +'\n')
            myfile.write(str(age) +'\n')



main()

<强>输出:

Enter first name of friend or Enter to quit: Mack
Enter age (integer) of this friend: 11
Enter first name of friend or Enter to quit: Steve
Enter age (integer) of this friend: 11
Enter first name of friend or Enter to quit: 

Process finished with exit code 0

答案 1 :(得分:0)

您的代码中存在一些错误,例如使用range()和缩进以及使用input作为字符串,而raw_input可能是更好的选择。

要做你想做的事,你应该把write放在循环的开头,在询问名字之后,检查它是否为空,如果是,break。代码如下:

def main():
    myfile = open('friends.txt','w')
    friend = raw_input('Enter first name of friend or Enter to quit')
    age = int(raw_input('Enter age (integer) of this friend'))

    while friend != '':

        while True:
            myfile.write(friend +'\n')
            myfile.write(str(age) +'\n')
            friend = raw_input('Enter first name of friend or Enter to quit')
            if not friend:
                break
            age = int(raw_input('Enter age (integer) of this friend'))

        print('File was created')
        myfile.close()
main()