Modul 3 Python
Modul 3 Python
conditional statements are used to control the flow of a program based on certain
conditions. These statements allow the execution of different code blocks depending on
whether a specified condition evaluates to True or False.
Nested Conditionals
● The if Statement
● The if-else Statement
● The if-elif-else Statement
● Nested Conditionals
● Ternary Conditional Operator
● Truthy and Falsy Values
The if Statement
The if statement evaluates a specified condition, and if the condition is True, the
indented block of code beneath it is executed
the if-else statement is used to create conditional logic where a block of code is
executed if a specified condition is True, and a different block of code is executed if the
condition is False
This structure allows the program to take different paths based on whether the given
condition is met or not
Example : The if-else Statement
The if-elif-else Statement
If none of the conditions is True, the block of code under the else statement is executed.
Example : if-elif-else Statement
Ternary Conditional Operator
These expressions typically involve the use of comparison operators, logical operators,
and other constructs that yield boolean results
● Comparison Operator
● Logical Operator
● Membership Operator
● Nested Conditionals
● Ternary Conditional Operator
● Truthy and Falsy Values
Comparison Operator
== (equal to): Returns True if the values on both sides are equal.
!= (not equal to): Returns True if the values on both sides are not equal.
< (less than): Returns True if the value on the left is less than the value on the right.
> (greater than): Returns True if the value on the left is greater than the value on the right.
<= (less than or equal to): Returns True if the value on the left is less than or equal to the value on the right.
>= (greater than or equal to): Returns True if the value on the left is greater than or equal to the value on the
right.
Example : Comparison Operator
Logical Operator
Logical operators are used to combine boolean expressions. The common logical
operators in Python are:
● and: Returns True if both boolean expressions on the left and right are True.
● or: Returns True if at least one of the boolean expressions on the left or right is
True.
● not: Returns the opposite boolean value of the expression after it.
Example Logical Operator
Membership Operator
the try and except statements are used to handle exceptions, which are
events that can occur during the execution of a program and disrupt its
normal flow
By using try and except, you can catch and handle exceptions gracefully,
preventing the program from crashing and allowing for more robust error
handling.
Example Catching exceptions using try and except