Chapter 4: Control Structures - VinGok/Python-Basics GitHub Wiki
Control Structures
Control structures are used for any deviation from conventional top-down style of executing commands. Python provides three types of control structures.
- if-elif-else
- for
- while
if-elif-else
To be used for conditional execution of block of codes only once.
if boolean_expression1:
block 1
elif boolean_expression2:
block 2
...
elif boolean_expressionN:
block N
else:
block last
Example: Input a number and check if it is positive or negative or zero.
number = int(input("Enter a number: "))
if (number > 0):
print("You entered a positive number!")
elif (number < 0):
print("You entered a negative number!")
else:
print("You entered a zero!")
print("End of program.")
Output:
Enter a number: 10
You entered a positive number!
End of program.
Enter a number: -10
You entered a negative number!
End of program.
Enter a number: 0
You entered a zero!
End of program.
Example: Convert a user-input examination score to corresponding grade as per the following table.
Score | Grade |
---|---|
91-100 | A |
76-90 | B |
61-75 | C |
46-60 | D |
0-45 | F |
score = int(input("Enter the score: "))
if (score > 90 and score <=100):
print ("Grade: A")
elif (score > 75 and score <=90):
print ("Grade: B")
elif (score > 60 and score <=75):
print ("Grade: C")
elif (score > 45 and score <=60):
print ("Grade: D")
else:
print ("Grade: F")
print ("End of program!")
Output:
Enter the score: 30
Grade: F
End of program!
Enter the score: 65
Grade: C
End of program!
Programming Practice
1. Determine which of these categories a user-input integer belongs to: positive-even, positive-odd, negative-even, negative-odd, or zero.
for statement
Useful when a certain task is to be executed repeatedly a predetermined number of times.
for variable in sequence:
for_block
for i in 0, 10, 20, 30, 40, 50:
print(i)
print("End of for loop!")
Output:
0
10
20
30
40
50
End of for loop!
range (a, b) generates a sequence of values like a, a+1, a+2, ..., b-1 in ascending order.
for i in range(0,5):
print(i)
print("End of for loop!")
Output:
0
1
2
3
4
End of for loop!
range function for integers in descending order.
for i in range(5,0,-1):
print(i)
print("End of for loop!")
Output:
5
4
3
2
1
End of for loop!
Print contents in the same line.
for i in range(0,5):
print(i, end = " ")
print("End of for loop!")
Output:
0 1 2 3 4 End of for loop!
Example: Score to grade conversion for 6 courses.
Score | Grade |
---|---|
91-100 | A |
76-90 | B |
61-75 | C |
46-60 | D |
0-45 | F |
for i in range(1,7):
score = int(input("Enter the score: "))
if (score > 90 and score <=100):
print ("Grade: A")
elif (score > 75 and score <=90):
print ("Grade: B")
elif (score > 60 and score <=75):
print ("Grade: C")
elif (score > 45 and score <=60):
print ("Grade: D")
else:
print ("Grade: F")
print("End of the score to grade conversion!")
Output:
Enter the score: 10
Grade: F
Enter the score: 30
Grade: F
Enter the score: 40
Grade: F
Enter the score: 68
Grade: C
Enter the score: 95
Grade: A
Enter the score: 34
Grade: F
End of the score to grade conversion!
Programming Practice
2. Print all the integers between two user-input integers (both inclusive) that are divisible by 5 but not by 7.
3. Write a program to print all even numbers between two user-input integers.
Nested for loop: for loop inside a for loop. Useful when there are multiple varying entities.
for i in range(0,2):
for j in range(4,6):
print("i =", i, " j =", j)
print ("End of j loop")
print ("End of program")
Output:
i = 0 j = 4
i = 0 j = 5
End of j loop
i = 1 j = 4
i = 1 j = 5
End of j loop
End of program
Example: Print multiplication tables for 1 and 2 one below the other.
for i in range (1, 3):
for j in range (1, 11):
print (i, "X", j, "=" i*j)
print ("")
Output:
1 X 1 = 1
1 X 2 = 2
1 X 3 = 3
1 X 4 = 4
1 X 5 = 5
1 X 6 = 6
1 X 7 = 7
1 X 8 = 8
1 X 9 = 9
1 X 10 = 10
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
Programming Practice
4. Take a user-input integer m in the range 2 and 9 (both inclusive). Print a number triangle as shown below depending on m. For example, if m = 7 display the following.
7 6 5 4 3 2 1
6 5 4 3 2 1
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
while statement
Useful when the number of times a certain task is to be executed is unknown, but the loop termination condition is predetermined
while boolean_expression:
while_block
Example: Count the number of user inputs to exceed the total of 100.
total = 0
entries = 0
while (total < 100):
number = int(input("Enter the number: "))
total = total + number
entries = entries + 1
print ("Number of entries to exceed 100: ", entries)
Output:
15
25
35
45
End of program!
Example: Convert scores to grades until an invalid score (higher than 100) is entered
Score | Grade |
---|---|
91-100 | A |
76-90 | B |
61-75 | C |
46-60 | D |
0-45 | F |
score = int(input("Enter the score: "))
while (score <= 100):
if (score > 90):
print ("Grade: A")
elif (score > 75):
print ("Grade: B")
elif (score > 60):
print ("Grade: C")
elif (score > 45):
print ("Grade: D")
else:
print ("Grade: F")
score = int(input("Enter the score: "))
print("Ending the conversion since an invalid score was entered")
Output:
Enter the score: 12
Grade: F
Enter the score: 34
Grade: F
Enter the score: 90
Grade: B
Enter the score: 64
Grade: C
Enter the score: 122
Ending the conversion since an invalid score was entered
In-loop control statements
These statements are used to control execution inside a loop. There are two types:
- break
- continue
break statement
It is used to abruptly break out of a loop. In case of nested loops, the break statement forces the execution out of the loop in which it resides, and the execution continues with next iteration of the immediately outer loop.
Example: Print all integers between two user-input integers until the first number divisible by 10 occurs.
for i in range(1, 11):
if (i%7 == 0):
break
print(i, end = " ")
print('End of program execution')
Output:
1 2 3 4 5 6 End of program execution
Nested for loops example
for i in range (1, 5):
for j in range (1, 5):
if (i+j == 5):
break
print(i,j)
Output:
1 1
1 2
1 3
2 1
2 2
3 1
continue statement
It is used to skip a block of statements for that iteration. In nested loops, the code after the continue statement is skipped and the execution continues with next iteration in that loop.
for i in range(1, 11):
if (i%4 == 0):
continue
print(i)
Output:
1
2
3
5
6
7
9
10
Comparison between continue and continue break statements
for i in range (1, 5): for i in range (1, 5):
for j in range (1, 5): for j in range (1, 5):
if (i+j == 5): if (i+j == 5):
continue break
print(i,j) print(i,j)
Output:
1 1 1 1
1 2 1 2
1 3 1 3
2 1 2 1
2 2 2 2
2 4 3 1
3 1
3 3
3 4
4 2
4 3
4 4
Example:
Convert 6 valid scores to corresponding grades notifying the user when an invalid score (> 100) is entered.
valid_entries = 0
while (True):
score = int(input("Enter the score: "))
if (score > 100):
print("Please enter a valid score.")
continue
elif (score > 90):
print ("Grade: A")
valid_entries = valid_entries+1
elif (score > 75):
print ("Grade: B")
valid_entries += 1
elif (score > 60):
print ("Grade: C")
valid_entries += 1
elif (score > 45):
print ("Grade: D")
valid_entries += 1
else:
print ("Grade: F")
valid_entries += 1
if (valid_entries == 6):
break
print("Ending of the conversion")
Programming Practice
6. Write a program to print all integers between two user-input integers with two exceptions:
- Skip printing if the number is divisible by 10
- Exit the program if the number if divisible by 17.