python, continue

Asked 2 years ago, Updated 2 years ago, 74 views

Hello, masters! Corinne is posting a question!

numbers = [ (1,2),(10,0) ]

for a,b in numbers:
if b == 0:
    print("It cannot be divided by 0".")
    continue
print("{} divided by {} is {}".format(a,b,a/b))

If you run this,

1 divided by 2 is 0.5

It cannot be divided by zero. It comes out in two lines.

print ("cannot be separated by 0") Shouldn't this code come out first?
Why is this code the second time?

Thank you very much

python continue

2022-09-21 19:31

1 Answers

The code above is incorrectly indented and will cause an error. Let's assume that you did the right indentation below the for line.

numbers = [ (1,2),(10,0) ]

for a,b in numbers:
    if b == 0:
        print("It cannot be divided by 0".")
        continue
    print("{} divided by {} is {}".format(a,b,a/b))

a becomes 1 on the first iteration and 10 on the second iteration.

b becomes 2 on the first iteration and 0 on the second iteration.

That is, the if b == 0: condition is the condition that is satisfied on the second iteration.

In summary, dividing 1 by 2 in the first iteration results in 0.5 output, and then cannot be divided by 0 in the second iteration. is displayed.

These issues are easily identified when debugging on a line-by-line basis.

First of all, please use the pdb (http://pythonstudy.xyz/article/50%B%EB2%B%B%B%B%B%B%B%B%B%B%B%B%B%B%B%B%B%B%B%B%B%B%B%B%B


2022-09-21 19:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.