Python Numbers, Strings & Casting
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!
# 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)
Because integers in Python automatically expand to consume additional RAM digits, you can compute factorials like 100! or cryptographically large numbers without overflow.
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$).
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
Use / when you need precise floating-point decimals. Use // when you need whole integer bucket indexes or pagination calculations.
Strings are ordered sequences of Unicode characters. Slicing syntax is: string[start : stop : step]. Remember: strings are immutable (cannot be modified in place):
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
start: Starting index (inclusive).stop: Ending index (exclusive โ stops 1 character before!).step: Stride/increment (e.g.-1traverses the string in reverse!).
Formatted string literals (f-strings) allow you to interpolate variables directly with formatting specifiers (e.g. .2f for 2 decimal places, , for thousands separators):
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}")
{score:.2f}formats95.4567to95.46(rounded to 2 decimal places).{price:,.2f}inserts a comma thousands separator:1,499.50.
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.
Extract the first name, clean whitespace using strip(), and print a reversed greeting.
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])
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.