Table of Contents
- Example 1: Converting a String to an Integer
- Example 2: Converting an Integer to a Float
- Example 3: Converting a Float to an Integer
- Example 4: Converting a Number to a String
- Example 5: Converting User Input
- Example 6: Converting to Boolean
- Example 7: Converting a List to a Tuple
- Example 8: Converting a Tuple to a List
- Example 9: Converting a List to a Set
- Example 10: Multiple Type Conversions
- Common Mistakes
- Best Practices
- Key Points to Remember
Sometimes a value needs to be converted from one data type to another. This process is called type conversion.
For example:
- Converting user input (string) into an integer.
- Converting an integer into a floating-point number.
- Converting a number into a string for display.
- Converting collections such as lists into tuples.
Python provides several built-in functions to perform type conversion.
Some commonly used conversion functions are:
int()float()str()bool()list()tuple()set()
Example 1: Converting a String to an Integer #
main.py
number = "100"
value = int(number)
print(value)
print(type(value))
Output #
100
<class 'int'>
Explanation #
numberstores the string"100".- The
int()function converts the string into an integer. - The converted value is stored in
value. - The data type changes from
strtoint.
Example 2: Converting an Integer to a Float #
main.py
number = 25
value = float(number)
print(value)
print(type(value))
Output #
25.0
<class 'float'>
Explanation #
numberis an integer.- The
float()function converts it into a floating-point number. - The decimal part
.0is automatically added. - The resulting data type is
float.
Example 3: Converting a Float to an Integer #
main.py
price = 99.95
value = int(price)
print(value)
Output #
99
Explanation #
pricestores a floating-point number.int()removes the fractional part.- The value is truncated, not rounded.
- Therefore,
99.95becomes99.
Example 4: Converting a Number to a String #
main.py
age = 25
text = str(age)
print(text)
print(type(text))
Output #
25
<class 'str'>
Explanation #
ageis an integer.str()converts the integer into a string.- This is useful when combining numbers with text.
Example 5: Converting User Input #
main.py
age = int(input("Enter your age: "))
print(age + 5)
Sample Input #
Enter your age: 25
Output #
30
Explanation #
input()returns a string.int()converts the string into an integer.- The program can now perform arithmetic operations.
Example 6: Converting to Boolean #
main.py
print(bool(1))
print(bool(0))
print(bool("Python"))
print(bool(""))
Output #
True
False
True
False
Explanation #
- Non-zero numbers evaluate to
True. - Zero evaluates to
False. - Non-empty strings evaluate to
True. - Empty strings evaluate to
False.
Example 7: Converting a List to a Tuple #
main.py
numbers = [10, 20, 30]
data = tuple(numbers)
print(data)
print(type(data))
Output #
(10, 20, 30)
<class 'tuple'>
Explanation #
numbersis a list.tuple()converts the list into a tuple.- The data type changes from
listtotuple.
Example 8: Converting a Tuple to a List #
main.py
numbers = (10, 20, 30)
data = list(numbers)
print(data)
print(type(data))
Output #
[10, 20, 30]
<class 'list'>
Explanation #
numbersis a tuple.list()converts the tuple into a list.- The resulting object is mutable.
Example 9: Converting a List to a Set #
main.py
numbers = [10, 20, 20, 30, 30]
data = set(numbers)
print(data)
Output #
{10, 20, 30}
Explanation #
set()converts the list into a set.- Duplicate values are automatically removed.
- Sets store only unique elements.
Example 10: Multiple Type Conversions #
main.py
value = "25"
number = int(value)
decimal = float(number)
text = str(decimal)
print(number)
print(decimal)
print(text)
Output #
25
25.0
25.0
Explanation #
"25"is first converted into an integer.- The integer is converted into a floating-point number.
- Finally, the floating-point number is converted into a string.
- Python allows multiple conversions in sequence.
Common Mistakes #
1. Converting an Invalid String to an Integer #
Incorrect
number = int("Hello")
Output #
ValueError: invalid literal for int() with base 10: 'Hello'
Reason
Only strings representing valid integers can be converted using int().
Correct
number = int("100")
2. Assuming int() Rounds Values #
Incorrect Assumption
print(int(9.9))
Incorrect Expectation #
10
Actual Output #
9
Reason
int() truncates the decimal part instead of rounding.
3. Forgetting to Convert User Input #
Incorrect
age = input("Enter age: ")
print(age + 5)
Output #
TypeError: can only concatenate str (not "int") to str
Reason
input() returns a string.
Correct
age = int(input("Enter age: "))
print(age + 5)
4. Assuming Every Value Can Be Converted #
Incorrect
value = float("Python")
Output #
ValueError: could not convert string to float: 'Python'
Reason
Only strings representing valid floating-point numbers can be converted using float().
Best Practices #
- Convert values only when necessary.
- Always validate user input before conversion in real-world applications.
- Remember that
int()truncates decimal values. - Use
str()when combining numbers with text. - Be aware that some conversions may raise exceptions if the value is invalid.
Key Points to Remember #
- Type conversion changes a value from one data type to another.
- Python provides built-in conversion functions such as
int(),float(),str(),bool(),list(),tuple(), andset(). input()returns a string, which often needs to be converted before performing arithmetic operations.int()truncates the fractional part of floating-point numbers.- Invalid conversions raise exceptions such as
ValueError. - Type conversion is widely used when processing user input and transforming data between different formats.