Python How to break loop with 0

Question:

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

Asked By: Glonza

||

Answers:

so,when you start the loop it ask you what number you want to enter and then the code checks if the number is == to 0. IF the number is equal to 0: break the loop. IF the number is equal to any other number it prints the "random_calculation" function

Answered By: Diego Ciprietti

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))
Answered By: Sembei Norimaki
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.