By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,587 Members | 1,168 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,587 IT Pros & Developers. It's quick & easy.

Is there a command for getting out of the function?

P: 2
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.

Expand|Select|Wrap|Line Numbers
  1. def user_guess(num):
  2.     if(num==rand_num):
  3.         print "hurrey! you guessed it right.\n"
  4.         another_try=raw_input("would you like to guess another number??\n")
  5.         if(another_try == "y" or another_try == "yes"):
  6.             num = int(input("Guess the number!\n"))
  7.             return num
  8.         else: 
  9.             print "okay! have a good day!"
  10.             sys.exit()
  11.  
  12.     elif(num>rand_num):
  13.         print "your guessed number is greater than the actual number,,\n"
  14.         guess_again=raw_input("would you like to guess the same number again??\n")
  15.         if(guess_again == "y" or guess_again == "yes"):
  16.             num=int(input("guess the number"))
  17.             user_guess(num)
  18.         else: #here i want to get out of the function only,I want the other part of the program to run
  19.     elif(num<rand_num):
  20.         print "your guessed number is lesser than the actual number,,\n"
  21.     else:
  22.  
can somebody help me out?(ignore if any other errors)
Jul 18 '19 #1
Share this Question
Share on Google+
4 Replies


dev7060
P: 92
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.
Jul 18 '19 #2

P: 1
I think you can use break
Jul 18 '19 #3

dev7060
P: 92
- 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.
Jul 18 '19 #4

Rabbit
Expert Mod 10K+
P: 12,359
You already know the command. In line 7 you get out of the function. You just need to do something similar again.
Jul 18 '19 #5

Post your reply

Sign in to post your reply or Sign up for a free account.