0

I've got a very basic problem with python variable scope. I tried to get fluent in python today and wrote a number guesser function which is called in a while loop. But the problem is, that It can't break the loop in this way. I know, that I can solve it, if I don't use the function and put all the if-else statements in the while "body". But I would like to solve this problem without changing the structure of the code. I tried to solve it with a return statement but I don't get it.

Thanks for your answers.

import random 
b = 53 #random.randint(0,100)
i = 0
def numberus_guesserus ():
  a = float(input("Guess a number between 0 and 100: "))
  if a==b:
    print("gg, correct!")
    i=5
  elif 100>a>b:
    print("Too high")
  elif a>100:
    print("You didn't get the rules ")
  else:
    print("Too low")
while i<5:
  print(i)
  i+=1
  numberus_guesserus ()
  if i==5:
    print("Number is: " + b)
  • 1
    If `a == b`, then `numberus_guesserus` should return `True`; otherwise, it should return `False`. Then you can put something like `if numberus_guesserus(): break` in your loop. – chepner May 23 '21 at 14:06
  • 2
    Functions communicate with external scopes using arguments and return values – Mad Physicist May 23 '21 at 14:07
  • See https://stackoverflow.com/questions/750136/how-is-returning-the-output-of-a-function-different-from-printing-it – OneCricketeer May 23 '21 at 14:09
  • 1
    you can just add `global i` in the beginning of your function and your exact code will work – Muhd Mairaj May 23 '21 at 14:12
  • @MuhdMairaj. At that point, why bother with functions in the first place? – Mad Physicist May 23 '21 at 14:13
  • @MadPhysicist I agree, i would recommend using `return` statements in the code... but since OP said he didnt want to change the structure of the code, and also because the `return` idea is already mentioned in the first comment. :) – Muhd Mairaj May 23 '21 at 14:18
  • OP, you say you tried using a return. I don't see any such attempt in the question. If you got an error, add a traceback – Mad Physicist May 23 '21 at 14:21

0 Answers0