Search code examples
pythonwhile-loopbreak

Python How to break loop with 0


I don't understand why is not working on my code

def random_calculation(num):
    return((num*77 + (90+2-9+3)))


while random_calculation:
    num = int(input("Pleace enter number: "))
    if num == "0":
        break
    else:
        print(random_calculation(num))

Can you guide me what is wrong here, i really dont understand


Solution

  • You have several errors in your code:

    You cannot do while random_calculation like this. You need to call the function, but since inside the loop you are already checking for a break condition, use while True instead.

    Also, you are converting the input to int, but then comparing agains the string "0" instead of the int 0

    Here's the corrected code:

    def random_calculation(num):
        # 90+2-9+3 is a bit strange, but not incorrect.
        return((num*77 + (90+2-9+3)))
    
    
    while True:
        num = int(input("Please enter number: "))
        if num == 0:
            break
        
        # you don't need an else, since the conditional would 
        # break if triggered, so you can save an indentation level
        print(random_calculation(num))