Python program मध्ये data वेगवेगळ्या types मध्ये असतो. कधी calculation करण्यासाठी value numeric type मध्ये हवी असते, कधी display करण्यासाठी string मध्ये convert करावी लागते, तर कधी एखादी value True किंवा False म्हणून evaluate करायची असते.
यासाठी Type Conversion समजणे अत्यंत महत्त्वाचे आहे.
या chapter मध्ये आपण Implicit Conversion, Explicit Conversion, int(), float(), str(), bool() आणि common conversion errors शिकणार आहोत.
Learning Outcomes#
हा chapter पूर्ण केल्यानंतर तुम्ही:
- Implicit आणि Explicit conversion मधला फरक explain करू शकाल.
- Python काही numeric calculations मध्ये type automatically कसा बदलतो हे ओळखू शकाल.
int(),float(),str()आणिbool()योग्य परिस्थितीत वापरू शकाल.- String मधील numeric data actual number मध्ये convert करू शकाल.
- Conversion नंतर resulting data type predict करू शकाल.
ValueErrorआणिTypeErrorसारख्या common conversion problems ओळखू शकाल.int()decimal part कसा handle करतो हे explain करू शकाल.bool()वापरताना empty आणि non-empty values मध्ये फरक समजू शकाल.- चुकीचे conversion करण्यापूर्वी input/value compatible आहे का याचा विचार करू शकाल.
1. Type Conversion म्हणजे काय?#
Type conversion is the process of changing a value from one data type to another data type.
याचा साधा अर्थ म्हणजे एका data type मधील value दुसऱ्या data type मध्ये बदलणे.
उदाहरण:
age_text = "25"
age = int(age_text)
print(age)
print(type(age))Expected Output:
25
<class 'int'>इथे:
"25"ही string आहे.
पण:
int("25")केल्यावर Python तिचे integer value 25 मध्ये conversion करतो.
महत्त्वाचे म्हणजे:
Value दिसायला number सारखी आहे म्हणून ती actual number असेलच असे नाही. तिचा data type महत्त्वाचा असतो.
उदाहरण:
price = "500"इथे 500 number सारखे दिसत असले तरी quotation marks मुळे ते str आहे.
2. Type Conversion ची गरज का पडते?#
Imagine तुम्ही shopping application तयार करत आहात.
एका product ची price:
price = 500आणि discount:
discount = 50दोन्ही numeric असल्यामुळे calculation सहज होईल.
final_price = price - discount
print(final_price)Output:
450पण जर price string स्वरूपात असेल:
price = "500"
discount = 50
final_price = price - discountहे valid नाही.
कारण Python ला string मधून integer subtract करता येत नाही.
म्हणून conversion आवश्यक आहे:
price = "500"
discount = 50
final_price = int(price) - discount
print(final_price)Output:
450Practical rule#
Calculation करण्यापूर्वी data योग्य numeric type मध्ये आहे का ते तपासणे आवश्यक असते.
3. Python मध्ये Type Conversion चे प्रकार#
Python मध्ये आपण या chapter मध्ये दोन मुख्य प्रकार समजणार आहोत:
Type Conversion
│
├── Implicit Conversion
│ Python automatically performs conversion
│
└── Explicit Conversion
Programmer explicitly requests conversionदोन्हींचा उद्देश data types compatible करणे असला तरी conversion कोण करतो यामध्ये मुख्य फरक आहे.
4. Implicit Conversion#
Implicit conversion is an automatic type conversion performed by Python when compatible data types are used together.
म्हणजे काही परिस्थितीत programmer ने conversion function explicitly call केलेले नसतानाही Python आवश्यक conversion automatically करतो.
Suppose:
quantity = 4
price = 99.5
total = quantity * price
print(total)
print(type(total))Expected Output:
398.0
<class 'float'>इथे:
quantityहा int आहे.
priceहा float आहे.
Calculation:
int × floatPython result float मध्ये देतो.
Conceptually:
4
int
\
→ numeric operation → 398.0
/
99.5
floatआपण manually असे लिहिले नाही:
float(quantity)तरीही calculation compatible करण्यासाठी Python numeric operation appropriate type मध्ये handle करतो.
आणखी एक उदाहरण#
number1 = 10
number2 = 2.5
result = number1 + number2
print(result)
print(type(result))Output:
12.5
<class 'float'>number1 हा int आहे.
number2 हा float आहे.
Result:
12.5हा float आहे.
Python असे का करतो?#
Now think carefully.
जर Python mixed numeric calculation मध्ये result integer ठेवला असता:
10 + 2.5तर .5 information हरवली असती.
म्हणून appropriate numeric result preserve करण्यासाठी result float होतो.
Implicit conversion सामान्यतः compatible numeric types सोबत दिसते. Python प्रत्येक वेगळ्या data type ला automatically compatible बनवत नाही.
उदाहरण:
number = 10
text = "20"
result = number + textPython text ला automatically integer मध्ये convert करत नाही.
म्हणून हे काम explicit conversion ने करावे लागेल.
5. Explicit Conversion#
Explicit conversion is a type conversion requested directly by the programmer using a conversion function.
म्हणजे programmer स्वतः Python ला सांगतो:
ही value मला दुसऱ्या type मध्ये convert करून दे.
Python मध्ये आपण commonly वापरतो:
int()
float()
str()
bool()उदाहरण:
price_text = "750"
price = int(price_text)
print(price)Output:
750इथे conversion automatic नाही.
आपण explicitly:
int(price_text)लिहिले आहे.
म्हणून हे Explicit Conversion आहे.
6. Implicit vs Explicit Conversion#
| Point | Implicit Conversion | Explicit Conversion |
|---|---|---|
| Conversion कोण करतो? | Python automatically | Programmer explicitly |
| Conversion function आवश्यक? | नाही | हो |
| Example | 10 + 2.5 | int("10") |
| Control | Python ठरवतो | Programmer ठरवतो |
| Common use | Compatible numeric operations | String ↔ number, number ↔ string इ. |
लक्षात ठेवा#
10 + 2.5→ Implicit
float(10)→ Explicit
7. int()#
int() converts a compatible value to an integer.
int() compatible value ला integer मध्ये convert करते.
String to Integer#
marks_text = "85"
marks = int(marks_text)
print(marks)
print(type(marks))Output:
85
<class 'int'>Flow:
"85"
str
↓ int()
85
intहे विशेषतः तेव्हा useful असते जेव्हा number string स्वरूपात उपलब्ध असतो.
Float to Integer#
price = 99.75
whole_price = int(price)
print(whole_price)Output:
99इथे एक अतिशय महत्त्वाचा मुद्दा आहे.
int() float ला nearest integer ला round करत नाही. ते fractional part remove करते.उदाहरण:
print(int(8.9))
print(int(8.1))Output:
8
8दोन्ही 8.
Negative number#
print(int(-8.9))Output:
-8यामुळे एक common misconception दूर होते.
int() म्हणजे:
roundingनाही.
ते fractional part काढून टाकते आणि result zero च्या दिशेने truncate होतो.
Integer ते Integer#
number = 25
result = int(number)
print(result)Output:
25Value आधीच compatible integer असल्यामुळे result तसाच integer राहतो.
8. int() सोबत Invalid String#
हे चालते:
number = int("100")पण हे चालत नाही:
number = int("hello")कारण "hello" ही valid integer representation नाही.
Python error देतो:
ValueErrorExample:
number = int("hello")Typical error:
ValueError: invalid literal for int() with base 10: 'hello'Root cause#
int() ला string मिळाली.
पण त्या string मधील content integer म्हणून interpret करता येत नाही.
9. एक महत्त्वाचा int() Trap#
Consider:
number = int("12.5")काही beginners विचार करतात:
"12.5" → 12.5 → 12पण int() असे automatic two-step conversion करत नाही.
"12.5" ही integer-formatted string नाही.
म्हणून:
int("12.5")ValueError देईल.
जर तुमच्याकडे decimal numeric string असेल तर compatible conversion:
number = float("12.5")
print(number)Output:
12.5या chapter च्या scope मध्ये महत्त्वाचा rule:
int() ला दिलेली numeric string integer format मध्ये असावी.10. float()#
float() converts a compatible value to a floating-point number.
float() compatible value ला decimal-capable floating-point number मध्ये convert करते.
Integer to Float#
quantity = 5
quantity_float = float(quantity)
print(quantity_float)
print(type(quantity_float))Output:
5.0
<class 'float'>Integer 5 चे float representation:
5.0String to Float#
temperature_text = "36.5"
temperature = float(temperature_text)
print(temperature)
print(type(temperature))Output:
36.5
<class 'float'>Flow:
"36.5"
str
↓ float()
36.5
floatInteger-formatted String to Float#
हे देखील valid आहे:
price = float("500")
print(price)Output:
500.0कारण "500" numeric value म्हणून float मध्ये represent करता येते.
11. Invalid float() Conversion#
हे valid:
float("19.95")पण:
float("nineteen")valid नाही.
Example:
price = float("nineteen")Typical result:
ValueErrorकारण Python ला "nineteen" हा text floating-point number म्हणून parse करता येत नाही.
12. int() vs float()#
| Value | Conversion | Result |
|---|---|---|
"25" | int("25") | 25 |
"25" | float("25") | 25.0 |
25 | float(25) | 25.0 |
25.9 | int(25.9) | 25 |
"25.9" | float("25.9") | 25.9 |
"25.9" | int("25.9") | Error |
Must Know#
Decimal string साठीfloat()वापरा.int()decimal-formatted string direct accept करत नाही.
13. str()#
str() converts a value to its string representation.
str() एखाद्या value ला text/string representation मध्ये convert करते.
Example:
score = 95
score_text = str(score)
print(score_text)
print(type(score_text))Output:
95
<class 'str'>Output मध्ये 95 दिसते म्हणून ते integer आहे असे समजू नका.
type() सांगते:
<class 'str'>14. Number आणि String एकत्र वापरण्याची समस्या#
Suppose:
age = 25
message = "Age: " + ageहे valid नाही.
कारण:
str + intdirectly concatenate करता येत नाही.
Correct approach:
age = 25
message = "Age: " + str(age)
print(message)Output:
Age: 25Flow:
25
int
↓ str()
"25"
str
"Age: " + "25"
↓
"Age: 25"Float to String#
price = 199.99
price_text = str(price)
print(price_text)
print(type(price_text))Output:
199.99
<class 'str'>Boolean to String#
status = True
status_text = str(status)
print(status_text)
print(type(status_text))Output:
True
<class 'str'>महत्त्वाचे:
Trueboolean आहे.
पण:
"True"string आहे.
दोन्ही visually similar वाटू शकतात, पण त्यांचे types वेगळे आहेत.
15. bool()#
bool() converts a value to either True or False based on its truth value.
bool() एखाद्या value ला तिच्या truth value नुसार True किंवा False मध्ये convert करते.
16. Numbers with bool()#
print(bool(1))
print(bool(10))
print(bool(-5))Output:
True
True
TrueNon-zero numeric values सामान्यतः:
Trueहोतात.
Zero:
print(bool(0))
print(bool(0.0))Output:
False
FalseBasic rule#
0 → False
0.0 → False
non-zero number → True17. Strings with bool()#
Empty string:
print(bool(""))Output:
FalseNon-empty string:
print(bool("Python"))Output:
TrueRule:
"" → False
"Python" → True
"0" → True
"False" → Trueइथे शेवटच्या दोन examples beginners साठी खूप महत्त्वाच्या आहेत.
18. bool("False") चे result True का?#
Consider:
print(bool("False"))Output:
Trueपहिल्यांदा हे चुकीचे वाटू शकते.
पण Python इथे "False" या word चा अर्थ analyze करत नाही.
तो पाहतो:
String empty आहे का?"False" ही non-empty string आहे.
म्हणून:
bool("False")Result:
Trueहेच:
bool("0")साठीही लागू होते.
"0" ही string आहे आणि ती empty नाही.
त्यामुळे result:
Trueअत्यंत महत्त्वाचे#
bool()string मधील शब्दाचा अर्थ तपासत नाही. Empty stringFalse; non-empty stringTrue.
19. Conversion Function Summary#
int(value)
↓
Integer
float(value)
↓
Floating-point number
str(value)
↓
String
bool(value)
↓
True / FalseExample:
value = "50"
print(int(value))
print(float(value))
print(bool(value))Output:
50
50.0
Trueआणि:
number = 50
print(str(number))Output:
50पण resulting type str असेल.
Practical / Real-World Application#
Scenario: Product Data Conversion#
Suppose application मध्ये product information अशी उपलब्ध आहे:
product_name = "Keyboard"
price_text = "1499.50"
quantity_text = "2"इथे:
price_text
quantity_textदोन्ही strings आहेत.
Calculation करण्यासाठी आपल्याला numeric types हवेत.
product_name = "Keyboard"
price_text = "1499.50"
quantity_text = "2"
price = float(price_text)
quantity = int(quantity_text)
total = price * quantity
print(product_name)
print(total)Expected Output:
Keyboard
2999.0Analysis#
Requirement:
Total price calculate करायची आहे.Available data:
"1499.50" → str
"2" → strNeeded data:
1499.50 → float
2 → intConversion:
"1499.50"
↓ float()
1499.50
"2"
↓ int()
2Calculation:
1499.50 × 2 = 2999.0Lesson#
Real applications मध्ये value कुठून आली यापेक्षा calculation करण्याच्या वेळी तिचा actual data type काय आहे हे अधिक महत्त्वाचे आहे.
Practical Example: Employee Information#
employee_id = 101
salary = 55000.50
employee_id_text = str(employee_id)
salary_text = str(salary)
print("Employee ID: " + employee_id_text)
print("Salary: " + salary_text)Output:
Employee ID: 101
Salary: 55000.5इथे numeric data display-oriented string तयार करण्यासाठी str() वापरला.
Practical Example: Availability Status#
stock = 5
available = bool(stock)
print(available)Output:
Trueकारण stock non-zero आहे.
जर:
stock = 0
available = bool(stock)
print(available)Output:
Falseया example मधून truth-value conversion समजते.
Common Mistakes & Misconceptions#
Mistake 1: Numeric-looking String म्हणजे Number समजणे#
Wrong understanding:
price = "500"आणि मग:
discounted_price = price - 50Problem#
price ही string आहे.
Correct understanding#
discounted_price = int(price) - 50Mistake 2: Python प्रत्येक String automatically number मध्ये convert करेल#
Consider:
number = 10
text = "20"
print(number + text)Beginner ला वाटू शकते result:
30पण Python string "20" ला automatically integer मध्ये convert करत नाही.
Correct:
number = 10
text = "20"
print(number + int(text))Output:
30Mistake 3: int() म्हणजे rounding#
Wrong assumption:
int(9.9)Result 10 येईल.
Actual result:
9कारण int() fractional part remove करते.
print(int(9.9))
print(int(-9.9))Output:
9
-9Mistake 4: int("12.5") valid आहे#
Wrong:
number = int("12.5")Problem:
"12.5" ही integer-formatted string नाही.
Better:
number = float("12.5")Output:
12.5Mistake 5: bool("False") म्हणजे False#
Wrong assumption:
bool("False")Result:
FalseActual:
Trueकारण "False" ही non-empty string आहे.
Mistake 6: "0" आणि 0 सारखेच आहेत#
print(bool(0))
print(bool("0"))Output:
False
TrueWhy?
0हा numeric zero आहे.
पण:
"0"ही non-empty string आहे.
Mistake 7: Invalid Text Numeric Conversion#
Wrong:
price = float("five hundred")Result:
ValueErrorRoot Cause#
Text valid numeric representation नाही.
Prevention#
Conversion करण्यापूर्वी value कोणत्या format मध्ये आहे याचा विचार करा.
Common Conversion Errors#
ValueError#
ValueError occurs when a function receives a value of an acceptable general type but the value cannot be converted as requested.
Type conversion context मध्ये याचा practical अर्थ:
Function ला string मिळू शकते, पण string मधील content required numeric format मध्ये नसते.
Example:
age = int("twenty")Result:
ValueErrorआणखी एक example:
price = int("19.99")Result:
ValueErrorTypeError#
TypeError occurs when an operation or function is used with an inappropriate type of value.
उदाहरण:
number = int(None)हे valid integer conversion नाही आणि TypeError येतो.
Beginner level वर मुख्य idea:
ValueError
→ value चा format conversion साठी योग्य नाही
TypeError
→ supplied value चा type operation/function साठी योग्य नाहीConversion Decision Guide#
जेव्हा conversion करायची असेल तेव्हा स्वतःला विचारा:
मला final value कशासाठी हवी आहे?
│
├── Whole-number calculation
│ → int()
│
├── Decimal calculation
│ → float()
│
├── Text representation
│ → str()
│
└── Truth-value check
→ bool()पण function निवडणे पुरेसे नाही.
Value compatible आहे का हेही पाहावे लागते.
उदाहरण:
"25" → int() ✔
"25.5" → int() ✘
"25.5" → float() ✔
"Python" → float() ✘Hands-On Practice#
Practice 1 — String to Integer#
Problem#
तुमच्याकडे:
items = "8"आहे.
त्याला integer मध्ये convert करून त्यात 2 add करा.
Learner Task#
Expected result:
10Hint 1#
items चा current type str आहे.
Hint 2#
int() वापरा.
Solution#
items = "8"
total = int(items) + 2
print(total)Output:
10Practice 2 — Price Conversion#
Problem#
price = "499.50"या value मध्ये 100.0 add करा.
Constraint#
Value decimal स्वरूपात preserve झाली पाहिजे.
Hint#
int() योग्य conversion आहे का याचा विचार करा.
Solution#
price = "499.50"
final_price = float(price) + 100.0
print(final_price)Output:
599.5Practice 3 — Create Display Text#
Problem#
score = 92यापासून:
Score: 92असा string तयार करा.
Solution#
score = 92
message = "Score: " + str(score)
print(message)Output:
Score: 92Practice 4 — Predict Truth Values#
Code run करण्यापूर्वी output predict करा:
print(bool(0))
print(bool(10))
print(bool(""))
print(bool("Python"))
print(bool("False"))Solution#
False
True
False
True
TrueReason:
- numeric zero →
False - non-zero number →
True - empty string →
False - non-empty string →
True
Practice 5 — Find the Problem#
Code:
quantity = "5"
price = 100
total = quantity * price
print(total)Question:
हा code intended numeric multiplication करतो का?
Think First#
quantity चा type कोणता आहे?
Better Solution#
quantity = "5"
price = 100
total = int(quantity) * price
print(total)Output:
500Important Observation#
Python मध्ये string multiplication चे वेगळे behavior असू शकते, त्यामुळे code error देतोच असे नाही; पण इथे business requirement numeric multiplication आहे. त्यामुळे correct data type वापरणे आवश्यक आहे.
Interview Preparation#
1. What is type conversion in Python?
Type conversion is the process of converting a value from one data type to another data type.
What the interviewer is testing: Whether you understand the basic purpose of data type conversion.
2. What is implicit type conversion?
Implicit type conversion is an automatic conversion performed by Python when compatible data types are used together.
Example:
result = 10 + 2.5The result is 12.5, which is a float.
3. What is explicit type conversion?
Explicit type conversion is a conversion requested directly by the programmer using functions such as int(), float(), str(), or bool().
Example:
number = int("25")4. What is the difference between implicit and explicit conversion?
Implicit conversion is performed automatically by Python, while explicit conversion is requested by the programmer using a conversion function.
5. What does int() do?
int() converts a compatible value to an integer.
Examples:
int("25")
int(10.8)produce:
25
106. Does int() round a floating-point number?
No. int() does not round a floating-point number to the nearest integer. It removes the fractional part by truncating toward zero.
Example:
int(9.8)returns:
97. What happens when int("10.5") is executed?
It raises a ValueError because "10.5" is not a valid integer-formatted string.
If the value represents a decimal number, float("10.5") can be used instead.
8. What does float() do?
float() converts a compatible value to a floating-point number.
Example:
float("19.5")returns:
19.59. What does str() do?
str() converts a value to its string representation.
Example:
str(100)returns the string:
"100"10. Why may str() be required when concatenating text with a number?
Python does not directly concatenate a string and an integer using +.
Example:
"Age: " + str(25)converts the integer to a string before concatenation.
11. What does bool() do?
bool() converts a value to True or False according to its truth value.
For example:
bool(0)returns False, while:
bool(10)returns True.
12. What is the result of bool("")?
It returns:
Falsebecause an empty string is false in a Boolean context.
13. What is the result of bool("False")?
It returns:
Truebecause "False" is a non-empty string. bool() does not interpret the meaning of the text inside the string.
Common weak answer: "It returns False because the string contains the word False."
That answer is incorrect.
14. What is the difference between bool(0) and bool("0")?
bool(0)returns False because numeric zero is false.
bool("0")returns True because "0" is a non-empty string.
15. What is a common reason for ValueError during numeric conversion?
A ValueError commonly occurs when the supplied string does not contain a valid representation of the requested numeric type.
Example:
int("hello")raises a ValueError.
16. Can Python automatically convert "20" to 20 when adding it to an integer?
No.
Example:
10 + "20"does not perform automatic string-to-integer conversion.
The programmer must explicitly convert the value:
10 + int("20")Quick Revision#
Type Conversion#
Changing a value from one data type to another.
Implicit Conversion#
Python performs conversion automatically when appropriate.
10 + 2.5Result:
12.5Type:
floatExplicit Conversion#
Programmer requests conversion.
int("25")
float("25.5")
str(100)
bool(1)int()#
int("20") # 20
int(9.8) # 9Remember:
int("9.8")is invalid.
float()#
float("20.5") # 20.5
float(20) # 20.0str()#
str(25)creates string representation "25".
bool()#
0 → False
0.0 → False
"" → False
non-zero → True
non-empty str → TrueTherefore:
bool("False")is:
TrueConversion Errors#
int("hello")→ ValueError
int("12.5")→ ValueError
Use conversion compatible with the actual value format.
You Should Now Be Able To#
After completing this chapter, you should independently be able to:
- explain type conversion
- distinguish implicit and explicit conversion
- predict the type produced by mixed
intandfloatarithmetic - convert integer-formatted strings using
int() - convert decimal-formatted strings using
float() - convert numeric values to strings using
str() - reason about
bool()results for numbers and strings - explain why
bool("False")returnsTrue - identify invalid numeric conversions
- distinguish a numeric-looking string from an actual number
- recognize common
ValueErrorsituations - select an appropriate conversion function for a simple requirement
Final Challenge#
Scenario#
एका simple billing system मध्ये खालील values मिळाल्या आहेत:
product = "Mouse"
price = "799.50"
quantity = "2"
discount = 100Requirement:
pricedecimal number मध्ये convert करा.quantityinteger मध्ये convert करा.price * quantitycalculate करा.- त्यातून
discountsubtract करा. - Final message तयार करा:
Mouse final price: 1499.0Constraints#
- Original values unnecessarily बदलू नका.
- Appropriate conversion functions वापरा.
- Calculation numeric types वर करा.
- Final output message तयार करताना required string conversion करा.
Hint 1#
price मध्ये decimal point आहे.
Hint 2#
quantity whole number आहे.
Hint 3#
Numeric calculation पूर्ण झाल्यानंतर display string तयार करा.
Solution#
product = "Mouse"
price = "799.50"
quantity = "2"
discount = 100
numeric_price = float(price)
numeric_quantity = int(quantity)
total = numeric_price * numeric_quantity
final_price = total - discount
message = product + " final price: " + str(final_price)
print(message)Expected Output:
Mouse final price: 1499.0Reasoning#
"799.50"
↓ float()
799.50
"2"
↓ int()
2
799.50 × 2
↓
1599.0
1599.0 - 100
↓
1499.0
1499.0
↓ str()
"1499.0"हा challenge float(), int(), numeric calculation आणि str() एकत्र वापरतो.