0% found this document useful (0 votes)
10 views16 pages

Lec 4

Uploaded by

Natnael Belayneh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views16 pages

Lec 4

Uploaded by

Natnael Belayneh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Computer

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 condition: • Most other programming


languages use {}
# code to run if condition is true
Conditionals

name = "John Doe"

if name == "John Doe":


print("Hello, world!")
Chained Conditionals
• Elif statements are used to run code if a condition is not true, but another
condition is true.
Note: Each condition is checked in order. If the first is false, the next is checked,
and so on. If one of them is true, the corresponding branch runs and the
statement ends. Even if more than one condition is true, only the first true
branch runs.

if condition1:
# code to run if condition1 is
true
elif condition2:
# code to run if condition2 is
true
Conditionals

name = "John Doe"


if name == "John Doe":
print("Hello, John Doe!")
elif name == "Jane Doe":
print("Hello, Jane Doe!")
Conditionals
Else statements are used to run code if none of the other conditions are true.

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)

if((Value > 0) and (Value <= 10)):


print(Value)
Common Errors

if((Value < 0) and (Value > 10)):


print(Value)
Common Errors

if((1.11 - 1.10) == (2.11 -2.10)):


print(‘Equal’)

You might also like