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).
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