Decision Making

If statement

  • The If statement allows us to execute code with conditions.

  • Colon is added to an If statement and everything inside if needs to be idented with either tab or 4 spaces.

  • Here is an example, where a code checks whether age is a variable greater than 18:

age = 20
status = "Child"
if age > 18:
	status = "Adult" # If age is greater than 18, status changes to "Adult" string.
age += 1 # Age will add one.

If - Else

  • If allows execution of a code if a conditions is met, Else is used when the code needs to execute something else, if the condition is not met.

  • Here is the same example from before, with else added onto it:

age = 15
status = "None"
if age >= 18:
	status = "Adult"
else:
	status = "Young"
  • elif can be used to make another condition, if first one isn’t met.

  • Can be added and infinite amount of times.

age = 68
status = "None"
if age < 18:
	status = "Young"
elif age >= 18 and age <= 65:
	status = "Adult"
else:
	status = "Old"

Nested if - Else

  • Allows to check multiple condition by placing one if-else statement inside another.

  • Here is an example, where the second if-else is only executes when the first condition is true:

age = 18
if age >= 18:
	print("You are an adult")
	if age >= 21:
		print("You can drink alcohol in the US")
	else:
		print("You cannot drink alcohol in the US") # 			 Here an extra condition is added onto the first condition.
else:
	print("You are a minor")