Introduction

Control Structures are a way to specify flow of control in programs. Any algorithm or program can be more clear and understood if they use self-contained modules called as logic or control structures. It basically analyzes and chooses in which direction a program flows based on certain parameters or conditions.
Python has three types of control structures:

  • Sequential - default mode
  • Selection - used for decisions and branching
  • Repetition - used for looping, i.e., repeating a piece of code multiple times.

Sequential

Flow of a program that executes in an order, without skipping, jumping or switching to another block of code. Most of the processing, even some complex problems, will generally follow this elementary flow pattern.

Selection (Conditional Flow)

In Python, the selection statements are also known as Decision control statements or branching statements.
The selection statement allows a program to test several conditions and execute instructions based on which condition is true.
Some Decision Control Statements are:

  • Simple If
  • if-else
  • nested if
  • if-elif-else

These types of control structures were covered in tutorial 2

Repetition

A repetition statement is used to repeat a group(block) of programming instructions.

In Python, we generally have two loops/repetitive statements:

  • for loop
  • while loop

Repetition: for loop 

A for loop allows Python to keep repeating code a set number of times. It is sometimes known as a counting loop because you know the number of times the loop will run before it starts.

Examples:

for j in range(0,10):
	print(j)

In this example, the outputs would be 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. When it gets to 10 the loop would stop so 10 would not be shown in the output.

for i in range(10,1,-3):
	print(i)

This range will subtract 3 from i each time. The output will be: 10, 7, 4.

Repetition: while loop

A while loop allows code to be repeated an unknown number of times as long as a condition is being met. This may be 100 times, just the once or even never. In a while loop the condition is checked before the code is run, which means it could skip the loop altogether if the condition is not being met to start with. It is important, therefore, to make sure the correct conditions are in place to run the loop before it starts.

Examples

m = 5
i = 0
while i < m:
     print(i, end = " ")
     i = i + 1

 

n = 1 
while n < 5: 
	print("Hello World !") 
	n = n+1 
	if n == 3: 
		break

In Python, we can use the break statement to end a while loop prematurely.

 

Examples

EXO IV.1

Question. Ask the user to enter their name and then display their name three times using a for loop.

Answer. 

name = input("Enter your first name : ")

for i in range(3):
    print(name)

 EXO IV.2

Question. Alter program IV.1 so that it will ask the user to enter their name and a number and then display their name that number of times.

Answer. 

name = input("Enter your first name : ")
number = int(input("Enter a number : "))

for i in range(number):
    print(name)

 EXO IV.3

Question. Write a program that displays all integers from 8 to 23 (including bounds) using a for loop.

Answer. 


for i in range(8,24):
    print(i, end = "-")

 EXO IV.4

Question. Write a program that asks the user to type 10 integers and displays their sum.

Answer. 

sum = 0
for i in range(10):
    number = int(input("Type an integer : "))
    sum = sum + number

print("The sum is : ",sum)

 EXO IV.5

Question. Write a program to display the first 7 multiples of 7.

Answer. 

count = 0
for i in range(1,200):
    if i%7 == 0:
        print(i, end=" ")
        count = count + 1
        if count == 20:
            break

 EXO IV.6

Question. Ask the user to enter their name and display each letter in their name on a separate line.

Answer. 

name = input("Enter your name : ")
for j in name:
    print(j)

 EXO IV.7

Question. Set the total to 0 to start with. While the total is 50 or less, ask the user to input a number. Add that number to the total and print the message “The total is... [total]”. Stop the loop when the total is over 50 .

Answer. 

total = 0
while total <= 50 :
    number = int(input("Enter a number : "))
    total = total + number
    print("The total is : ", total)

 EXO IV.8

Question. Ask the user to enter a number. Keep asking until they enter a value over 5 and then display the message “The last number you entered was a [number]” and stop the program.

Answer. 

number = 0
while number <= 5:
    number = int(input("Enter a number : "))
print("The last number you entered was a ",number)

 EXO IV.9

Question. Write a program that asks the user to type 10 integers and displays the smallest of these integers.

Answer. 

for i in range(10):
    number = int(input("Enter an integer : "))
    if i == 0:
        smallest = number
    else:
        if number < smallest:
            smallest = number

print("The smallest number is : ", smallest)

 EXO IV.10

Question. Ask which direction the user wants to count (up or down). If they select up, then ask them for the top number and then count from 1 to that number. If they select down, ask them to enter a number below 20 and then count down from 20 to that number. If they entered something other than up or down, display the message “I don’t understand”.

Answer. 


direction = " "
while direction != "u" and direction != "d":
    direction = input("Do you want to count up or down (u/d) ? ")
    direction = direction.lower()

if direction == "u":
    number = int(input("What is the top number ? "))
    for i in range(1,number+1):
        print(i)
        
elif direction == "d":
    number = int(input("Enter a number below 20 : "))
    for i in range(20, number-1, -1):
        print(i)

 EXO IV.11

Question. Create a variable called compnum and set the value to 50. Ask the user to enter a number. While their guess is not the same as the compnum value, tell them if their guess is too low or too high and ask them to have another guess. If they enter the same value as compnum, display the message “Well done, you took [count] attempts”.

Answer. 

compnum = 75
guess = int(input("Can you guess the number I am thinking of ? "))
count = 1
while guess != compnum:
    if guess < compnum:
        print("Too low")
    else:
        print("Too high")
    count = count +1
    guess = int(input("Have another guess : "))

print(f"Well done, you took {count} attempts")
        

 EXO IV.12

Question. Ask the user to enter a number between 10 and 20. If they enter a value under 10, display the message “Too low” and ask them to try again. If they enter a value above 20, display the message “Too high” and ask them to try again. Keep repeating this until they enter a value that is between 10 and 20 and then display the message “Thank you”.

Answer. 

number = int(input("Enter a number between 10 and 20 :"))
while number<10 or number>20:
    if number<10:
        print("Too low")
    else:
        print("Too high")
    number = int(input("Try again :"))
print("Thank you")

 EXO IV.13

Question. Write a program that asks the user to enter an integer N and displays the following figure.

N=1

*

N=2

**

*

N=3

***

**

*

Answer. 

N = int(input("N="))

for i in range(N):
    for j in range(N-i):
        print("*",end="")
    print("\n") # to jump a line

 

0 comment

There are no comments yet.

Log in to leave a reply

Related posts

Developing a Web Application with Django Part 1: Getting Started

1/12/2021

Developing a Web Application with Django Part 2: Templates

15/12/2021

Developing a Web Application with Django Part 3 : Models

7/1/2022