programming constructs Flashcards
Sequence
Code is executed line-by-line, from top to bottom.
Branching
A certain block of code is run if a specific condition is met, using IF statements. This is also known as ‘selection’.
Iteration
A block of code is executed a certain number of times or while a condition is met. Iteration uses FOR, WHILE or REPEAT UNTIL loops.
iteration can be
count controlled-
for loop
~~~
for count in range (0,10):
print (“hi there”)
~~~
iteration can be
condition controlled example
while loop
~~~
import random
randomNumber=random.randint(0,10)
player guess = input(“which number am i thinking of”)
while int (playerGuess) != int(randomNumber):
playerGuess=input (“which number am i thinking of?”)
print (“you win”)
~~~
nest instruction example
while/if
import random playerResponse=input ("would u like to play a game?") while playerResponse == 'yes' randomNumber = random.randint(0,10) playerGuess == radnomNumber: if playerGuess == randomNumber: print ("you win") elif int (playerGuess)> int (randomNumber): print ("ur guess is too high") elif int (playerGuess)< int (randomNumbeer): print ("ur guess is too low") player response = input("would you like to play a game")
IF statement code
import random randomNumber=random.randint(0,10) if playerGuess== randomNumber: print ("you win") print ("thanks for playing")
IF ELSE statement code
import random randomNumber = ra som.randint (0,10) playerGuess= input (which number am i thinking of") if playerGuess == random number: print ("you win") else: print ("you lose")
ELIF statement code
import random randomNumber= random.randint (0,10) playerGuess=input("which number am i thinking of") if playerGuess == randomNumber: print("you win") ELIF int(playerGuess) > (randomNumber: print("too high") ELIF int(playerGiess)< (randomNumber: print("too low:)
while loops
used to repeat an instruction(or sequence of instructions) and loop until a condition is met
condition controlled loop
for loop
execute an instruction (or squence of instructions) a set.number of times
we creaste a variable called ‘count’ and set it to zero. every time the code inside the loop is executed count is incremented by 1.
when count reaches the value set by the programmer, the computer stops ececuted the code inside the loop and moves to the next instruction outside the loop.
count controlled
nesting
when you place one construct within of another.