Codezilla
Codezilla

Reputation: 95

Why does my break call the previous function

I have two functions and the first one calls the second one. However, when I break out of the second function it displays text from an if statement in the first function. What I don't understand, is why is the second function calling the first? Secondly, I do not understand why it would execute code from an if statement where the condition has never been met.

#! /usr/bin/env python

'''A sorting app where the user gets to choose 

between options and the options are ranked by 

likes in a file stored on a file'''

import sys
import random
import pickle 

def intro():
    greeting = '''\nWelcome to chooser where your voice gets to be heard

Press Enter to begin greatness
Press anything else to be immediately banned
>>'''
    enter = raw_input(greeting).lower()
    if enter == '':
        main()
    if enter == 'admin':
        print 'Entering Admin menu\n'
        admin()
    else:
        print '''\nDid you think I was kidding?!
You're gone!\n'''
        sys.exit()
# Enters the main program if the user presses Enter or else it quits 
def main():
    count = 0
    while True:
        nav = '''Type Go to play
Type Q to quit
Type admin to go to admin
>>'''
        start = raw_input(nav).lower()
        if start == 'q':
            print '\nThank you for playing\nBye!\n'
            break
        else:
            print 'Any other key restarts the function'
def chooser():
    pass
if __name__ == '__main__':
    intro()

'''                         -----Questions-----
Why does this function when it expires run the intro function instead of just 
running out of scope????'''

This is what prints out of the terminal:

terminal output

Upvotes: 0

Views: 46

Answers (1)

TulkinRB
TulkinRB

Reputation: 610

basically at the part:

if enter == '':
    main()
if enter == 'admin':
    print 'Entering Admin menu\n'
    admin()
else:
    print '''\nDid you think I was kidding?!

you have two seperete statements, one 'if' and one 'if-else' following it. the first checks if the input is '', this condition holds in your example, so main() is called and everythig is fine. when main() returns, you exit the first statement and enter the second, which checks if the input is admin (this is false), and if not it does the printing.

the logic here is:

  • if enter is '', run main().
  • if enter is 'admin', run admin().
  • if enter is not 'admin', print the message.

the else part is not related at all to the first if (only to the second). what you need to do is to replace the second 'if' with an 'elif', thus making a single 'if-elif-else' statement, so the logic will be:

  • if enter is '', run main().
  • if enter is not '', and enter is 'admin', run admin().
  • if enter is not '', and not 'admin', print the message.

Upvotes: 1

Related Questions