CzSzPzTz
CzSzPzTz

Reputation: 39

breaking a loop when enter is pressed

I'm trying to break the loop once Enter is pressed, while writing data to a file. This is what I have so far. I also don't want to limit the number of time the loop is run either... (example output is below)

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()

This is how to output is supposed to be when its ran right.

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

Upvotes: 0

Views: 443

Answers (2)

Chris
Chris

Reputation: 16147

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()

Output:

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

Upvotes: 1

Brian
Brian

Reputation: 1667

You had a couple of errors in your code, such as using range() and indentation and using input for a string, when raw_input may have been a better choice.

To do what you want, you should put the write at the beginning of your loop, and after asking for the name, check if it's empty and, if it is, break. Code is below:

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()

Upvotes: 0

Related Questions