Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

Python print different output if change order of if else


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because the the code start checking from the if part and then goes further elif parts if the previous one is false.

Basically, the number which is divisible by both 3 and 5 will meet the first if logic as it is divisible by 3 also in your second code, so it will execute that if and won't go further.

Here this code will execute like :

  1. first it will check if(number%3 == 0), if it is true then it will print("Fizz") and rest of the elif and else will not be checked.
  2. If 1 is not true then it will check elif(number%5 == 0)
  3. Then by this way it will go down.
if(number % 3 == 0):
        print("Fizz")
    elif(number % 5 == 0):
        print("Buzz")
    elif(number % 3 == 0 and number % 5 == 0): #this line not use first and output never have "fizzbuzz"
        print("FizzBuzz")
    else:
        print(number)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...