Care All Solutions

Basic Operators

Operators are symbols that perform specific operations on one or more values. Python supports several types of operators:

Arithmetic Operators

Used for basic mathematical operations:

  • +: Addition
  • -: Subtraction
  • *: Multiplication
  • /: Division
  • %: Modulus (remainder)
  • //: Floor division (integer division)
  • ****: Exponentiation

Python

x = 10
y = 3
print(x + y)  # Output: 13
print(x - y)  # Output: 7
print(x * y)  # Output: 30
print(x / y)  # Output: 3.3333333333333335
print(x % y)  # Output: 1
print(x // y)  # Output: 3
print(x ** y)  # Output: 1000

Comparison Operators

Used to compare values:

  • ==: Equal to
  • !=: Not equal to
  • <: Less than
  • >: Greater than
  • <=: Less than or equal to
  • >=: Greater than or equal to

Python

x = 10
y = 5
print(x == y)  # Output: False
print(x != y)  # Output: True
print(x > y)  # Output: True

Logical Operators

Used to combine conditional statements:

  • and: Both conditions must be true
  • or: At least one condition must be true
  • not: Negates a condition

Python

x = True
y = False
print(x and y)  # Output: False
print(x or y)  # Output: True
print(not x)  # Output: False

Assignment Operators

Used to assign values to variables:

  • =: Simple assignment
  • +=: Add and assign
  • -=: Subtract and assign
  • *=: Multiply and assign
  • /=: Divide and assign
  • %=: Modulus and assign
  • //=: Floor division and assign
  • ****: Exponentiation and assign

Python

x = 5
x += 3  # Equivalent to x = x + 3
print(x)  # Output: 8

Other Operators

  • Identity operators: is and is not (compare object identities)
  • Membership operators: in and not in (check for membership in sequences)

What is the difference between arithmetic and comparison operators?

Arithmetic operators perform mathematical calculations, while comparison operators compare values.

What is the modulus operator (%) used for?

The modulus operator returns the remainder of a division operation.

What is the purpose of logical operators?

Logical operators are used to combine conditional statements.

How is the order of operations determined in Python?

Python follows the standard mathematical order of operations (PEMDAS/BODMAS).

Can I change the order of operations using parentheses?

Yes, parentheses can be used to override the default order of operations.

What is the difference between / and //?

/ performs regular division, while // performs floor division (returns the largest integer less than or equal to the quotient).

Read More..

Leave a Comment