Skip to content

Numbers & Type Casting ๐Ÿš€

Mentor's Note: In programming, a 5 (number) and a "5" (text) look similar, but they behave differently. Casting is how we tell Python to switch between these "modes." ๐Ÿ’ก


๐ŸŒŸ The Scenario: The Currency Exchange ๐Ÿ’ฑ

Imagine you are traveling from the US to India.

  • The Logic: You have Dollars ($), but the shop only accepts Rupees (โ‚น). You must go to a counter and convert your money. ๐Ÿ“ฆ
  • The Result: The value stays the same (you are just as rich), but the type of currency changes so you can use it. This is Type Casting. โœ…

๐Ÿ“– Concept Explanation

1. Python Numeric Types

  • int: Whole numbers. 1, 100, -5.
  • float: Numbers with decimals. 3.14, -0.001.
  • complex: Numbers with an imaginary part. 1+2j.

2. Implicit Casting (Automatic) ๐Ÿช„

Python automatically converts one type to another if it's safe (e.g., adding an integer to a float).

x = 5    # int
y = 2.5  # float
z = x + y # z becomes 7.5 (Automatic float)

3. Explicit Casting (Manual) ๐Ÿ› ๏ธ

You use "Constructor" functions to force a change: - int(): Truncates decimals (3.9 -> 3). - float(): Adds .0 to integers. - str(): Turns numbers into text.


๐ŸŽจ Visual Logic: The Conversion Flow

graph LR
    A["String '10' ๐Ÿ”ก"] -- int() --> B["Integer 10 ๐Ÿ”ข"]
    B -- float() --> C["Float 10.0 ๐Ÿ’ฒ"]
    C -- str() --> D["String '10.0' ๐Ÿ”ก"]

๐Ÿ’ป Implementation: Casting Lab

# ๐Ÿ›’ Scenario: Calculating a bill from user input
# ๐Ÿš€ Action: Converting string input to numbers

# User inputs are ALWAYS strings by default ๐Ÿ”ก
input_price = "19.99"
input_quantity = "5"

# ๐Ÿ› ๏ธ Explicit Casting
price = float(input_price)
quantity = int(input_quantity)

total = price * quantity

print(f"Grand Total: โ‚น{total} ๐Ÿ›๏ธ")

๐Ÿ“Š Sample Dry Run (Truncation)

Variable Instruction Final Value Why?
x int(5.9) 5 Decimal is discarded, NOT rounded! โš ๏ธ
y float(10) 10.0 Decimal point added.

๐Ÿ“‰ Technical Analysis

  • Range: Unlike C++ or Java, Python integers have arbitrary precision, meaning they can grow as large as your computer's memory allows! ๐Ÿคฏ

๐ŸŽฏ Practice Lab ๐Ÿงช

Task: The Price Fixer

Task: You have a price 99.99. Write a program that converts this price to an integer and prints the "discounted" whole-number price. Hint: Use int(). ๐Ÿ’ก


๐Ÿ’ก Pro Tip: "Make it work, make it right, make it fast." - Kent Beck


โ† Back: Variables | Next: Arithmetic Operators โ†’