1. Python
  2. Fundamentals
  3. Operators

Python Operators

Last updated:

Arithmetic Operations

Standard math operators:

a = 10
b = 5

sum = a + b
difference = a - b
product = a * b
quotient = a / b

print(sum, difference, product, quotient)

Other arithmetic operators:

  • Modulus (%): returns the remainder when the first number is divided by the second number.
  • Exponentiation (**): raises the first number to the power of the second number.
  • Floor Division (//): divides the first number by the second number and rounds down to the nearest integer.
a = 10
b = 5

remainder = a % b
exponentiation = a ** b
floor_division = a // b

print(remainder, exponentiation, floor_division)

String Manipulation

Concatenation - using the ‘+’ operator.

string1 = "Hello"
string2 = "World"

combined_string = string1 + " " + string2
print(combined_string)

Slicing - extracting a substring from a string.

text = "Python programming"

substring = text[0:6]
print(substring)

String Formatting - various ways, including the f-string, which allows you to embed expressions within string literals.

name = "John"
age = 30

formatted_string = f"My name is {name}, and I am {age} years old."
print(formatted_string)

Boolean Operators

a = True
b = False

print(a and b)
print(a or b)
print(not a)

Type Conversions

Built-in functions:

  • int(): converts a value to an integer.
  • float(): converts a value to a floating-point number.
  • str(): converts a value to a string.
  • bool(): converts a value to a boolean.
  • list(): converts a value to a list.
  • tuple(): converts a value to a tuple.
  • set(): converts a value to a set.
  • frozenset(): converts a value to a frozenset.
  • dict(): converts a value to a dictionary.
  • complex(): converts a value to a complex number.
  • bytes(): converts a value to a bytes object.
  • bytearray(): converts a value to a bytearray object.
  • memoryview(): converts a value to a memoryview object.
integer = 42
floating_point = 3.14
string = "123"

converted_float = float(integer)
converted_int = int(floating_point)
converted_str = str(integer)

print(converted_float, converted_int, converted_str)