Programming Fundamentals
Basic Programming Constructs
Basic Programming Constructs
Understanding the three fundamental constructs of programming is essential for controlling the flow of a program. These constructs are sequence, selection, and iteration.
Sequence
Definition: The execution of statements one after another in the order they are written.
Example:
print("Hello") print("World")
This will output:
Hello World
Selection
Definition: Making decisions in a program based on conditions. This is usually implemented using
if
,else if
, andelse
statements.Example:
age = 18 if age >= 18: print("You are an adult.") else: print("You are a minor.")
This will output:
You are an adult.
Iteration
Definition: Repeating a block of code multiple times. There are two main types of iteration:
- Count-controlled loops: Repeat a specific number of times, typically using
for
loops. - Condition-controlled loops: Repeat until a condition is met, typically using
while
loops.
- Count-controlled loops: Repeat a specific number of times, typically using
Count-controlled Example:
for i in range(5): print(i)
This will output:
0 1 2 3 4
Condition-controlled Example:
i = 0 while i < 5: print(i) i += 1
This will output:
0 1 2 3 4
Understanding these constructs allows for the development of structured and efficient programs that can handle complex tasks by controlling the flow of execution.
Inifinite loops
A condition controlled loop needs to have its condition set before entry and then reset or it will run forever.
This example here will never see i reach 5 and so will loop forever
i = 0
while i < 5:
print(i)
Loop not entered
This example never see's entry into the loop as i has not been set beforehand
while i < 5:
print(i)
i=i+1
Loops for Validation
Validation is when you check if a data entered is sensible. A loop can be used to do a validation check. If the data isn't valid then the program will loop continuously until a valid piece of data is entered.
password = input("enter your password: ")
while len(password) < 8:
print("Error: Your password must be at least 8 characters.")
password = input("Please enter your password: ")
print("Password is the correct length")
This program keeps asking for user input until the password is greater than 8.