Skip to main content

Command Palette

Search for a command to run...

Day 2 โ€“ Python Operators & String

Published
โ€ข2 min readโ€ขView as Markdown

Operator

Operators are symbols that perform operations on variables and values.


๐Ÿ”ธ 1. Arithmetic Operators

Used for basic math operations.

a, b = 10, 3
print(a + b)   # 13
print(a - b)   # 7
print(a * b)   # 30
print(a / b)   # 3.33...
print(a % b)   # 1

๐Ÿ”ธ 2. Power Operator (**)

Raises one number to the power of another.

print(2 ** 3)  # 8

๐Ÿ”ธ 3. Floor Division (//)

Returns the largest integer after division.

print(10 // 3)  # 3

๐Ÿ”ธ 4. Assignment Operators

Used to assign or update variable values.

x = 5
x += 2
print(x)  # 7

๐Ÿ”ธ 5. Relational Operators

Used to compare values.

print(5 > 3)    # True
print(4 != 4)   # False

๐Ÿ”ธ 6. Logical Operators

Used to combine multiple conditions.

a, b = 10, 20
print(a < b and b > 15)  # True
print(not a > b)         # True

๐Ÿ”ธ 7. Bitwise Operators

Works at the binary level.

print(5 | 3)   # 7  -> OR
print(5 & 3)   # 1  -> AND
print(5 ^ 3)   # 6  -> XOR
print(5 << 1)  # 10 -> Left Shift
print(5 >> 1)  # 2  -> Right Shift
print(~5)      # -6 -> Complement

Strings in Python

A string is a sequence of characters enclosed in quotes.

name = "Python"

๐Ÿ”ธ 1. Types of Indexes

Each character in a string has a positive and negative index.

print(name[0])   # P
print(name[-1])  # n

๐Ÿ”ธ 2. Access Characters One by One

Use a loop:

for ch in name:
    print(ch)

๐Ÿ”ธ 3. Check Character in String

print("y" in name)  # True

๐Ÿ”ธ 4. Immutability of Strings

Strings canโ€™t be changed once created.

# name[0] = 'J'  โ†’ โŒ Error

๐Ÿ”ธ 5. First and Last Character

(name[0])    # P
print(name[-1])   # n

๐Ÿ”ธ 6. String Slicing

print(name[1:4])  # yth
print(name[:])    # Python

๐Ÿ”ธ 7. Common String Methods

text = "  Hello Python!  "
print(len(text))                # 17
print(text.strip())            # 'Hello Python!'
print(text.replace("Hello", "Hi"))  # '  Hi Python!  '
print(text.upper())            # '  HELLO PYTHON!  '