Home > database >  Python loop continues without stop
Python loop continues without stop

Time:10-31

import random

given_number = round(float(input("Enter a  number;\n")))
loop = True
while loop:
def Possibility(maximum):
    count = 0
    while count == 0:
        x = random.randint(0, maximum)
        if x:
            print("X is True")

        else:
            print("X is false")
            count  = 1
            print("Possibility calculated")
            answer = input("Do you want to try again? Y/N")
            if answer == "N":
                loop = False


   Possibility(given_number)

When I run the code even if I type N to answer as input program still continues to run any idea why this is happening?

CodePudding user response:

import random

given_number = round(float(input("Enter a  number;\n")))


def Possibility(maximum):
    count = 0
    while count == 0:
        x = random.randint(0, maximum)
        print(x)
        if x:
            print("X is True")
            return True
        else:
            print("X is false")
            count  = 1
            print("Possibility calculated")
            answer = input("Do you want to try again? Y/N")
            if answer == "N":
                return False

while Possibility(given_number):
    given_number = round(float(input("Enter a  number;\n")))
    Possibility(given_number)

the issue is, is that the function possibility was in a while loop, which means that the function would not be executed until it ended, which it couldnt, as the end condition was in the function. this should fix your issue, by making it loop the function itself rather than the definition. to break out of the loop, you would use the return function, which is an easy way to end the loop in this case.

  • Related