1

I try to learn the If statement forms integrated with For loop type, and i can't understand the differences between those codes because they give the same result:

grade = [100, 97, 73, 56, 78,34]
for i in range(0,len(grade)):
    if grade[i]%2 == 0:
        grade[i]= grade[i]+2
    if grade[i]%3 ==0:
        grade[i]= grade[i]+3
    if grade[i]%5 ==0:
        grade[i]= grade[i]+5
print grade

and this:

grade = [100, 97, 73, 56, 78,34]
for i in range(0,len(grade)):
    if grade[i]%2 == 0:
        grade[i]= grade[i]+2
        if grade[i]%3 ==0:
                grade[i]= grade[i]+3
            if grade[i]%5 ==0:
                grade[i]= grade[i]+5
print grade

2 Answers 2

2

When you have if statements one below another it's possible that something can match one OR another. When you have nested if statements, to go through your condition has to match one AND another.

Consider in your first case: 10. It will pass %2 == 0 and %5 == 0, but not the %3 == 0. In second case it will only pass the first test and won't go to the nested ones.

For instance: 30 will pass all the if statements in both case.

Sign up to request clarification or add additional context in comments.

2 Comments

i try it now- the second case go throe the 3 conditions
Yes, because you add your 2, 3 and 5 when previous condition matched. In case of 100, which passed first test, you add 2, which gives you 102 and pass second test and then gives you 105, so it passes also third one. It will go through all three ifs, but not all the time.
1

Both code is same but the main difference is first code contains three if condition that executed top to bottom or one by one and second code contains three nested if condition statement that execute if first statement is true

learn more from c-sharpcorner.com

1 Comment

Is your answer much different from the accepted answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.