Programming selection and iteration Flashcards
Selection - if statement
Selection or conditional statements execute a block of code based on the result of some test or condition we have set in the code
Testing to see whether the result is TRUE or FALSE and we can set different actions depending on the result of our test.
Format for an IF statement is:
IF Condition = True
THEN execute instructions 1
END IF
A condition is an expression that has a value of TRUE or FALSE. If the condition is true then the instructions are executed
Indentation
Indentation signifies the start and end of a block of code
Correct indentation is crucial, or the program may either not run, or give an incorrect result
Selection - if else statement
Sometimes, the IF statement also contains instructions to be carried out if the condition is False
IF Condition = True
THEN execute instructions 1
ELSE
THEN execute instructions 2
END IF
Selection: nesting if statements
We can also use IF/ELIF statements to check sub-conditions in a program:
x=5
y=8
if x == y:
print(“x and y are equal.”)
else:
if x < y:
print(“x is less than y.”)
else:
print(“x is greater than y.”)
Selection - comparison and logical operators: ==
Equality operator
checks whether both values are the same
Selection - comparison and logical operators: !=
Not equal to
Selection - comparison and logical operators: >
Greater than
Selection - comparison and logical operators: <
Less than
Selection - comparison and logical operators: >=
Greater than or equal to
Selection - comparison and logical operators: <=
Less than or equal to
Selection - comparison and logical operators: AND
Checks whether both conditions are true or false
Returns true only when both conditions are true
Selection - comparison and logical operators: OR
Checks whether either of the conditions are true
Returns true when either input is true
Selection - comparison and logical operators: NOT
Reverses a Boolean value (true or false)
If true then it becomes false
If false then it becomes true
3 basic programming constructs
Sequence
Selection
Iteration
Iteration
Allows a group of statements in the code to be executed several times
Useful because we would otherwise have to write the instructions out the correct number of times
There are two different types of iteration – indefinite and definite
Both can be used but in some cases one is more appropriate than the other