Like this article? You must log in first!

How to Use an If, Elif, and Else Statement in Python

Categories: Tech | Pubby Cash Received:  0 | Click to Award

Do you know how to use an if statement in Python? If you do not know how you should read this article because it will teach you how. First of all, the if statement is written using the if keyword in Python. Python also supports the logical conditions of mathematics. Here is what an if statement can look like. a = 1 b = 2 if a < b:     print("a is less than b.") The code above basically means that a is equal to 1 and b is equal to 2. The if statement is saying that a is less than b. Since 1 is less than 2, this would print a is less than b.. You must also make sure that the print statement is indented after the if statement because Python relies on indentation. If you do not indent, an error will appear. There is also an elif statement. This statement means that if the previous conditions were not true, then try this condition. Here is what an elif statement could look like. a = 3 b = 3 if b > a:     print("b is greater than a") elif a == b:     print("a and b are equal") The code above means that if b is greater than a, print b is greater than a. However, b is not greater than a. Since it is not, it moves on to the elif statement. The elif is saying that if a and be are equal, print a and b are equal. Since a and b are equal, this would print a and b are equal. Finally, there is the else statement. The else statement means that it catches anything which isn't caught by the preceding conditions. Here is what an else statement could look like a = 2 b = 1 if b > a:     print("b is greater than a") elif a == b:     print("a and b are equal") else:     print("a is greater than b" The code above means that if b is greater than a, print b is greater than a. However, it is not, so it then sees if a and b are equal. Since a and b are not equal, the else statement sees if a is greater than b. Since 2 is greater than 1, this would print a is greater than b. Hopefully, after reading this article, you have a good idea of how the if, elif, and the else statement work.


Published from: Pennsylvania US
Liked by: H2O, Andy Tang 

Daily Deals


MECHANICSBURG WEATHER