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