-4

When I wrote this code in python-2.7 I got a message that runs again and again, can someone tell me what's wrong with it?

num = raw_input("enter your number : ")

def calc():
    if num == "1":
        print "ok"
    else:
        print "right"
    calc()

calc()  

It prints ok or right over and over.

So what should I do if I want to go back to the initial state (asking for input) after each print?

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Zack.Rm
  • 15
  • 2

2 Answers2

2

It is repeating itself because you call calc() again inside the calc() function, making it an infinite loop.

def calc():
    if num == "1":
        print "ok"
    else:
        print "right"
    calc()  # <-- Why is this here?

So what should I do if I want to go back to the initial state (asking for input) after each print?

Then you need to ask for the input again inside the loop:

def calc():
    num = raw_input("enter your number : ")
    if num == "1":
        print "ok"
    else:
        print "right"
    calc()

calc() 
Praxis Ashelin
  • 5,137
  • 2
  • 20
  • 46
  • While this works in principle, it will actually recurse indefinitely, adding a new function call to the stack every time. While it'll take a while, it's a waste and the interpreter is going to crash when the maximum recursion depth is exceeded. – MisterMiyagi Oct 28 '15 at 21:40
  • I would almost agree with you, except code compiled with `gcc -O3` will perform tail recursion so there is no difference :) – Flying_Banana Oct 29 '15 at 14:04
  • @Fyling_Banana It's python, not C/++. CPython may be compiled with `-O3`, the code it executes isn't. See also http://stackoverflow.com/a/13592002/5349916. In fact, `def foo(): foo()` is enough to test this. – MisterMiyagi Oct 30 '15 at 10:08
1

If you keep calling the same function over and over again, you will reach a stack overflow sooner or later. In order to repeat something indefinitely, use a loop, e.g. for or while.

def calc():
  while True:
    num = raw_input("enter your number : ")
    if num == "1":
      print "ok"
    else:
      print "right"

calc()

You should also definitely consider adding a condition that exits your loop. For example, checking whether the input is "q" and then executing break:

  while True:
    num = raw_input("enter your number : ")
    if num == "q":
      break
    elif num == "1":
      print "ok"
    else:
      print "right"
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119