Again, another hard question. So Ive got a function, and ive got a couple of try and exception in it, and basically what i need is, if those exception give me an error, i want that function to go to an end. So, how am i suppose to do this. I have tried "break", but it only works for "while", am i right? I also tried "pass" but it also doesnt work, so how can i do this? Thanks everyone.

Recommended Answers

All 3 Replies

to end a function, simply place return at the place where you want to break the function.

for example:

def something():
    try:
        #something
    except SomeError:
        return False

As ultimatebuster explain return get you out of a function and break get you out off a while loop.
An example.

def find_father():
    pass

def main():
    '''Main menu and info ''' 
    while True:               
        print 'Father finder'
        print '(1) 1 - Find a Father'        
        print '(Q) Quit' 
        choice = raw_input('Enter your choice: ') 
        if choice == '1':
            find_father()       
        elif choice.lower() == 'q': 
            return #Get out of while loop
        else: 
            print 'Not a correct choice:', choice 

if __name__ == '__main__':
    main()

I we take out while loop out off the function,we use break.

while True:               
    print 'Father finder'
    print '(1) 1 - Find a Father'        
    print '(Q) Quit' 
    choice = raw_input('Enter your choice: ') 
    if choice == '1':
        print 'Find father'      
    elif choice.lower() == 'q': 
        break #Get out off the while loop
    else: 
        print 'Not a correct choice:', choice

Thank you snippsat for the example and also, thanks ultimatebuster, that did the trick ;) Marking it as solved

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.