-2

Currently I have this function:

x = 0
limit = 10
y = 7
def basic(x):
    global y
    while x <= limit:
        if x == 0 or 1:
            y += 1
            basic(x+1)
            return x
        else:
            y += 2
            basic(x+1)
            return x

basic(x)
print(y)

When I print y it returns 18 which means that it is stuck in the if statement and would not go to the else statement but x does stop at the limit hence y = 18. I looked up various sources online but I cannot get an exact clear visualization of my problem.

ᴀʀᴍᴀɴ
  • 4,443
  • 8
  • 37
  • 57
lee.edward01
  • 453
  • 1
  • 6
  • 16
  • 6
    `if x==0 or 1` always returns `True` , you need to change it to `if x==0 or x==1`. – ᴀʀᴍᴀɴ May 21 '18 at 16:55
  • 1
    i.e. you want `if x == 0 or x == 1`, or even `if x in range(1)` – Calum You May 21 '18 at 16:56
  • 2
    or mayb `if x < 2` – Barmar May 21 '18 at 16:57
  • 1
    @Aran-Fey I'm not sure this is the right way to say to some newbie that your code is not great, maybe writing an answer with modified version is better aproach. – ᴀʀᴍᴀɴ May 21 '18 at 17:01
  • @Aran-Fey I apologize for my code, I'm not trying to implement this anywhere or turn it in as homework or anything like that, I was just learning python in my free time and was writing random code to try to understand how functions work. It would be great if you could show me a function that does the same thing but more efficiently and it would also be a good learning experience for me! – lee.edward01 May 21 '18 at 17:07
  • It would help if you would explain what the function is supposed to do. – Aran-Fey May 21 '18 at 17:08

1 Answers1

5

Your problem is probably

if x == 0 or 1:

Acutally, that will firstly test if x == 0, and if x != 0 that will test if 1 is True. Since 1 is always True, that branch will always get executed.

You're probably looking to do

if x == 0 or x == 1:
Gregoire Lodi
  • 557
  • 2
  • 10