Lec 4
Lec 4
Programming: Lecture
4
Outline
• Conditionals
Conditionals
• Writing programs, we almost always need the ability to check conditions and
change the behaviour of the program accordingly.
• Conditionals are used to make decisions in Python. They allow you to run
different code depending on the value of a variable or expression.
Conditionals
Simple conditional statement: • Python uses indentation to
delineate blocks of code
if condition1:
# code to run if condition1 is
true
elif condition2:
# code to run if condition2 is
true
Conditionals
if condition1:
# code to run if condition1 is true
elif condition2:
# code to run if condition2 is true
else:
# code to run if none of the conditions are true
Conditionals
name = "John Doe"
if name == "John Doe":
print("Hello, John Doe!")
elif name == "Jane Doe":
print("Hello, Jane Doe!")
else:
print("Hello, stranger!")
Example
Demo
Example
Write a function for a computation that accepts two numbers and tells if the first number is a
multiple of the second number
Demo
Nested Conditionals
if(<conditional statements>):
if(<conditional statements>):
<if block>
else:
<else block>
else:
<else block>
Example
Write a function that checks if a number is divisible by 2 and 3.
Demo
Common Errors
if((Value > 0) or (Value <= 10)):
print(Value)