Welcome to the CSC Q&A.
Get help and give help!
Write great code!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+7 votes

In the code that I did for the class practice I seemed to be able to use them interchangeably, could someone give me an explanation of the three and in what scenarios it will be important to have them used appropriately?

asked in CSC201 Spring 2021 by (8 points)

2 Answers

+4 votes

"if" is always the first in a sequence. after the code gets to the "if" statement, either the condition of the statement is true, and it runs the if code, or its false, and then the code checks for attached elif/else. for example,

   if num > 0:
        print('positive')
   elif num < 0:
        print('negative')
   else:
        print('0')

first, the code checks 'if num > 0". if num is positive, the code prints 'positive' and then ignores the elif and else lines. since the if condition was true, it is done with this if grouping. if the number is negative, the code moves past the top 'if' line and checks then next part: "elif num < 0". if the number is negative, then this code runs, prints 'negative', and ignores the else statement. If the number is neither positive nor negative(which of course means it is zero) then the code skips 'if' and 'elif', and runs the code under "else" The else statement only runs if all if and elifs above it do not.

so the difference is that the code always checks to see if an 'if' statement is true, checks 'elif' statements only if each 'if' and 'elif' statement above it is false, and 'else' runs only when the conditions for all attached 'if' and 'elif' statements are false.

answered by (8 points)
+1 vote

If checks are always executed, elif only if the preceding statement is false,
the same process work for else

answered by (8 points)
...