Python Numbers, Strings & Casting

๐Ÿ Python 3.12+ ๐ŸŸข Chapter 4 of 65 ๐Ÿ“‚ Phase 1: Python Basics ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: int (Bignum) ยท float (IEEE 754) ยท complex ยท Slicing [::] ยท F-Strings ยท Type Casting
Master Python numeric computation with unlimited integer precision, IEEE 754 floating point arithmetic, string sequence indexing, modern f-string format specifiers, and implicit/explicit type casting.
1Numeric Types & Unlimited Integer Precision (Bignum)

Python 3 includes three built-in numeric primitives: int, float, and complex.

In languages like C, C++, or Java, integers are fixed to 32 bits (maximum value $2,147,483,647$) or 64 bits. In Python 3, integers have arbitrary precision (Bignum arithmetic). CPython dynamically allocates memory digits (in 30-bit chunks) to store integers of any magnitude without integer overflow bugs!

๐Ÿ’ป Example 1: Numeric Primitives & Arbitrary Precision
# 1. Calculating 2 raised to power 100 (Astronomically huge number!)
huge_num = 2 ** 100
print("2 ** 100 is:")
print(huge_num)

# 2. Float and Complex numbers
pi_val = 3.1415926535
complex_num = 3 + 4j

print("\nFloat Pi:", pi_val)
print("Complex real part:", complex_num.real, "| Imaginary part:", complex_num.imag)
๐Ÿ” Unlimited Integer Capacity:

Because integers in Python automatically expand to consume additional RAM digits, you can compute factorials like 100! or cryptographically large numbers without overflow.

2Arithmetic Operators Breakdown

Python provides 7 core arithmetic operators with distinct type-promotion rules:

  • + (Addition), - (Subtraction), * (Multiplication)
  • /: True Division โ€” ALWAYS returns a float (e.g. 10 / 2 -> 5.0).
  • //: Floor Division โ€” Discards remainder and rounds toward $-\infty$ (e.g. 15 // 4 -> 3, -15 // 4 -> -4).
  • %: Modulus โ€” Calculates remainder after division.
  • **: Exponentiation โ€” Power calculation ($a^b$).
๐Ÿ’ป Example 2: Arithmetic Operators Breakdown
a = 15
b = 4

print("Addition (+):", a + b)         # 19
print("Subtraction (-):", a - b)      # 11
print("Multiplication (*):", a * b)   # 60
print("True Division (/):", a / b)    # 3.75 (Float)
print("Floor Division (//):", a // b) # 3 (Int)
print("Modulus (%):", a % b)          # 3 (Remainder)
print("Power (**):", 2 ** 5)          # 32
๐Ÿ” Division Difference:

Use / when you need precise floating-point decimals. Use // when you need whole integer bucket indexes or pagination calculations.

3String Indexing, Slicing & Immutability

Strings are ordered sequences of Unicode characters. Slicing syntax is: string[start : stop : step]. Remember: strings are immutable (cannot be modified in place):

๐Ÿ’ป Example 3: String Indexing and Slicing
word = "Python"

print("First char [0]:", word[0])            # P
print("Last char [-1]:", word[-1])           # n
print("Slice [0:3]:", word[0:3])             # Pyt (stops 1 index before 3)
print("Every 2nd char [::2]:", word[::2])     # Pto
print("Reversed string [::-1]:", word[::-1]) # nohtyP
๐Ÿ” Slicing Parameters:
  • start: Starting index (inclusive).
  • stop: Ending index (exclusive โ€” stops 1 character before!).
  • step: Stride/increment (e.g. -1 traverses the string in reverse!).
4Modern F-Strings Formatting (Python 3.6+)

Formatted string literals (f-strings) allow you to interpolate variables directly with formatting specifiers (e.g. .2f for 2 decimal places, , for thousands separators):

๐Ÿ’ป Example 4: Modern F-Strings Formatting
student = "Balaji"
score = 95.4567
price = 1499.50

# Modern f-strings format variables cleanly:
print(f"Student: {student}")
print(f"Score (2 decimal places): {score:.2f}")
print(f"Price formatted: Rs.{price:,.2f}")
๐Ÿ” Format Specifiers:
  • {score:.2f} formats 95.4567 to 95.46 (rounded to 2 decimal places).
  • {price:,.2f} inserts a comma thousands separator: 1,499.50.
โš ๏ธ Common Developer Pitfall: Attempting to Cast Float Strings Directly with int()

Calling int("45.89") raises a ValueError: invalid literal for int() with base 10. You must first convert the string to float and then to integer: int(float("45.89")) to truncate decimals safely.

๐Ÿ’ป Hands-on Interactive Practice Challenge

Extract the first name, clean whitespace using strip(), and print a reversed greeting.

Python 3 Practice Challenge โ–ถ Run in Compiler
user_input = "  python developer  "
clean_text = user_input.strip()

print("Original:", repr(user_input))
print("Cleaned:", clean_text)
print("Uppercase:", clean_text.upper())
print("Reversed:", clean_text[::-1])
Run This Challenge in Online Python IDE โ†’
โ“ Frequently Asked Questions (FAQ)

Q Why are strings in Python immutable?

Immutability makes strings hashable (allowing them to serve as dictionary keys and set members), memory-efficient (enabling CPython string interning optimizations), and inherently thread-safe in concurrent applications.

Q What is the maximum integer size in Python 3?

There is no fixed maximum size. Python 3 dynamically allocates as many 30-bit memory digits as required to represent the number, constrained only by available computer RAM.

Q What is the difference between str() and repr()?

str() produces a human-readable display string intended for end users. repr() produces an unambiguous, developer-focused representation showing exact type and escape characters.

OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Python 3.12+ runtime ยท Last updated August 2026