Operators in Python
Operators in Python
Topics Covered:
• Operators in Python
• Conditional Statements
Operators in Python
In Python, operators are special symbols or keywords that perform
operations on operands. Here's an overview of the main types of
operators in Python:
Arithmetic Operators:
1. Addition (+): Adds two operands.
2. Subtraction (-): Subtracts the right operand from the left operand.
5. Floor Division (//): Divides the left operand by the right operand and
returns the largest integer less than or equal to the result.
7. Exponentiation (): Raises the left operand to the power of the right
operand.
Comparison Operators:
1. Equal to (==): True if the operands are equal.
2
2. Not equal to (!=): True if the operands are not equal.
3. Greater than (>): True if the left operand is greater than the right
operand.
4. Less than (<): True if the left operand is less than the right operand.
6. Less than or equal to (<=): True if the left operand is less than or
equal to the right operand.
3
Logical Operators:
1.
3. Logical NOT (not): True if the operand is false, and vice versa.
Membership Operators:
In Python, membership operators are used to test whether a value is a
member of a sequence or collection. There are two membership
operators: `in` and `not in`. They are commonly used with strings, lists,
tuples, and other iterable data types.
1. `in` Operator:
4
The `in` operator returns `True` if a specified value is found in the
sequence.
Example:
5
Conditional Statements
1. `if` Statement:
The `if` statement is used to execute a block of code if a specified
condition evaluates to `True`. If the condition is `False`, the code block
is skipped.
2. `else` Statement:
The `else` statement is used to define a block of code that will be
executed if the `if` condition is `False`.
6
3. `elif` Statement:
The `elif` statement allows you to check multiple conditions. It comes
after an `if` statement and before an optional `else` statement. If the `if`
condition is `False`, it checks the `elif` conditions one by one until a
true condition is found, and the corresponding block of code is
executed.
7
These conditional statements are crucial for controlling the program's
logic and allowing it to make decisions based on different conditions.
They provide the foundation for building more sophisticated and
responsive programs in Python.
8
Sample Program:
1) Write a python program to determine whether a number is odd
or even
Answer: