Flow of control
if
/elif
/else
statements are used to make complex decisions. It's perhaps the most used statement to control program flow.
Let's input a choice, then see the visual result in CodeCraft world:
Example: choice
Let's build 5 white columns, then depending on your choice, one of them will be highlighted with a specific color:
# 5 white columns
pool = [3, 2, 4, 8, 1]
for i in range(5):
column(i, -20, pool[i], 'quartz')
Run the program to see the 5 white columns, then add the following code:
choice = int(input('Enter your choice of number from 1 to 5: '))
if choice == 1:
print('1, blue')
column((choice-1), -20, pool[choice-1], 'linen_blue')
elif choice == 2:
print('2, red')
column(choice-1, -20, pool[choice-1], 'linen_red')
elif choice == 3:
print('3, yellow')
column(choice-1, -20, pool[choice-1], 'linen_yellow')
elif choice == 4:
print('4, pink')
column(choice-1, -20, pool[choice-1], 'linen_pink')
elif choice == 5:
print('5, purple')
column(choice-1, -20, pool[choice-1], 'linen_purple')
else:
print( 'You entered an invalid choice. No column is chosen')
Run the whole program a few times. Each time enter a different number to see the chosen column highlighted with a color.
Such as: 4, pink
Extra Practice
Let's make a square that is a solid color but has a different color on its diagonals. This can be done with an if
statement inside nested for
loops:
# Square_X
for i in range(-5, 6):
for j in range(-5, 6):
if abs(i) == abs(j):
m = 'box_black'
else:
m = 'box_blue'
block(i, 9+j, -10, m)