Skip to content

Numbers & Type Casting πŸš€ΒΆ

Prerequisites: Python Variables

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 β†’