Is there a command for getting out of the function?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • swaroop11
    New Member
    • Jul 2019
    • 2

    Is there a command for getting out of the function?

    I just started with python. I tried to write a small code for guessing a number. I wondered if we can get out of the function only, not the whole program.

    Code:
    def user_guess(num):
    	if(num==rand_num):
    		print "hurrey! you guessed it right.\n"
    		another_try=raw_input("would you like to guess another number??\n")
    		if(another_try == "y" or another_try == "yes"):
    			num = int(input("Guess the number!\n"))
    	        return num
    		else: 
    			print "okay! have a good day!"
    			sys.exit()
    			
    	elif(num>rand_num):
    		print "your guessed number is greater than the actual number,,\n"
    		guess_again=raw_input("would you like to guess the same number again??\n")
    		if(guess_again == "y" or guess_again == "yes"):
    			num=int(input("guess the number"))
    			user_guess(num)
    		else: #here i want to get out of the function only,I want the other part of the program to run
    	elif(num<rand_num):
    		print "your guessed number is lesser than the actual number,,\n"
    	else:
    can somebody help me out?(ignore if any other errors)
  • dev7060
    Recognized Expert Contributor
    • Mar 2017
    • 655

    #2
    One way of doing this is to use labels and goto. But Python doesn't support them. However, you can use something like this if that serves your purpose. It enables to transfer the flow of control to a label.

    Comment

    • Gbolly
      New Member
      • Jul 2019
      • 1

      #3
      I think you can use break

      Comment

      • dev7060
        Recognized Expert Contributor
        • Mar 2017
        • 655

        #4
        - break statement is used to terminate the loop and jump the control to the first statement after the loop body. But here, it appears the post is meant to change the flow of control in case of functions.

        - @swaroop11 The statement "sys.exit() " is responsible for the closing of the program. It can also be removed if the purpose is not so in the else case.

        Comment

        • Rabbit
          Recognized Expert MVP
          • Jan 2007
          • 12517

          #5
          You already know the command. In line 7 you get out of the function. You just need to do something similar again.

          Comment

          Working...