Python Conditional and Loop Statements
Abdulmutalib Idris
Head of IT and Media / Full Stack Developer @ Agro Preciso LTD
If ... Elif ... Else
If keyword
if is use to check a condition and and action is taken if the condition is true. Example:
num1 = 9
num2 = 16
if num1 < num2:
print("num1 is less than num2")
In the above we created to variables num1 and num2. They are then use in the statement to test is num1 is less than num2 and clearly 9 is less than 16 so the output will be num1 is less than num2.
Note: Python relies on indenting to categories block of code so always follow the indenting rules as states in our second class "Python Installation Hello World Program"
Elif Keyword
elif is use to tell python that if the pervious conditions were not true then try the this condition. Example:
num1 = 9
num2 = 16
if num1 > num2:
print("num1 is greater than num2")
elif num2 > num1:
print("num2 is greater than num1")
Else Keyword
else is use to catch every other condition not capture by all the preceding conditions. Example:
num1 = 9
num2 = 9
if num1 > num2:
print("num1 is greater than num2")
elif num2 > num1:
print("num2 is greater than num1")
else:
print("num1 is equal to num2")
Short Hand If
A conditional statement that will executing only one statement, can be put on same line as the statement. Example:
num1 = 9
num2 = 16
if num1 < num2: print("num1 is less than num2")
Short Hand If ... Else
If your if statement have only one statement to execute and the else also have one statement to execute, they can all be put on one line and this is call Ternary Operators, or Conditional Expressions. Example:
num1 = 9
num2 = 16
print("num1 is greater than num2") if num1 > num2 else print("num2 is greater than num1")
this can also be implemented for multiple else as shown below:
num1 = 9
num2 = 9
print("num1 is greater") if num1 > num2 else print("num1 = num2") if num1 == num2 else print("num2 is greater")
Using And and Or Keyword
They a logical operators use to combine conditional statements
num1 = 9
num2 = 16
num3 = 10
if num1 < num2 and num1 < num3:
print("Both conditions are True")
elif num1 < num2 or num1 < num3:
print("At least one of the conditions is True")
Using Not Keyword
Is a logical operator use to reverse the result of the conditional statement
num1 = 9
num2 = 16
if not num1 > num2:
print("num1 is NOT greater than num2")
Nested If
When you have an if statement inside another if statement that is called nested if. Example:
num1 = 9
if num1 > 5:
print("Bigger than 5, ")
if num1 > 10:
print("and also bigger than 10")
else:
print("but not bigger than 10")
Note: there must be at least one statement after an if statement, but if for some reason there is no statement, you can use the 'pass' keyword to avoid error
num1 = 9
if num1 > 5:
pass
Python While Loops
It execute a set of statement as long as a condition is true.
In the below example, i is the indexing variable set to 1 and the loop print i as long as it is less than 10. And i is increment after each loop.
i = 1
while i < 10:
print(i)
i += 1
Note: remember to increment i, or else you will create an infinity loop, a loop that will continue forever.
The break Statement
It is use to stop the loop at anytime even if the condition is still true
i = 1
while i < 10:
print(i)
if i == 6:
break
i += 1
领英推荐
Continue Statement
It is use to stop or skip current iteration and jump to the next
i = 0
while i < 10:
i += 1
if i == 3:
continue
print(i)
Else Statement
It is use to run a block of code once when the condition is no longer true
i = 1
while i < 10:
print(i)
i += 1
else:
print("i is no longer less than 10")
Python For Loops
for loop is use to iterate over collections of data or sequence like string, and any of the Python collections of data datatype like List, Tuple, Set and Dictionary.
It do not really work like the for keyword in other programing languages it work more like an iterating method as found in object-orientated programming languages.
It execute a set of statement for each item in the collections of data or sequence. Example:
countries = ["Nigeria", "Ghana", "Cameroon", "South Africa"]
for x in countries:
print(x)
Looping Through a String
for x in "programming":
print(x)
Break Statement
It is use to stop the loop before it loop thorough all the items. Example:
countries = ["Nigeria", "Ghana", "Cameroon", "South Africa"]
for x in countries:
print(x)
if x == "Cameroon":
break
If you don't want "Cameroon" to be printed the loop can be implemented as such the break comes before the print statement
countries = ["Nigeria", "Ghana", "Cameroon", "South Africa"]
for x in countries:
if x == "Cameroon":
break
print(x)
Continue Statement
It is use to stop or skip current iteration and jump to the next
countries = ["Nigeria", "Ghana", "Cameroon", "South Africa"]
for x in countries:
if x == "Cameroon":
continue
print(x)
range() Method
for loop can also loop through set of code for a specified number of time, but to do this the range() method can be used, range() method returns a sequence of numbers starting from 0 by default and end at the specified number in the range() method. Example:
for x in range(10):
print(x)
Note: that range(6) is not the values of 0 to 6, but the values 0 to 5.
The default starting point of range() can be change by specifying a start point like below:
for x in range(3, 10):
print(x)
Else in For Loop
It specify the code to be executed when the loop is finished. Example:
for x in range(10):
print(x)
else:
print("Finished!")
Note: The else block will NOT be executed if the loop is stopped by a break statement.
Nested Loops
This is simple a loop inside a loop. A good example is trying to print values of items in a nested dictionary of student as below:
student1 = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
student2 = {
"id": "ST002",
"name": "Halimat Abdulmutalib",
"courses": 10,
"CGPA": 4.5
}
student3 = {
"id": "ST003",
"name": "Abdulmutalib Idris",
"courses": 9,
"CGPA": 3.0
}
students = {
"student1": student1,
"student2": student2,
"student3": student3
}
for x in students:
for y in students[x]:
print(students[x][y])
print ("---------------------------")
I included a print ("---------------------------") to draw lines so as to separate each group of outputs
Pass Statement
There must be at least one statement after a for loop, but if for some reason there is no statement, you can use the 'pass' keyword to avoid error
for x in "Hello":
pass
????? ??????? ??????? ??????? ?? ????? ? ??????? ???? ??? ??????? ??????.
1 年Thank you sir.