Python From Beginner to Advanced

0% completed

Previous
Next
Python - Type Conversions

Type conversion in Python allows you to change the data type of a value to another type. This can be done either implicitly (automatically by Python) or explicitly (manually by the programmer). Proper understanding of both types of conversions is essential for accurate data manipulation and ensuring the correctness of program operations.

Image

Implicit Casting (Automatic Type Conversion)

Implicit casting occurs when Python automatically converts one data type to another without any explicit instruction from the programmer. This often happens during operations involving binary operands of different types.

Example

Automatically converting an integer to a float to perform addition.

Python3
Python3

. . . .

Explanation:

  • num_int = 6 assigns an integer value.
  • num_float = 1.5 assigns a float value.
  • The addition operation result = num_int + num_float causes num_int to be automatically converted to a float.
  • print("Result:", result) displays the float result of the addition.

Explicit Casting (Manual Type Conversion)

Explicit casting involves manually converting the data type of a value using Python's built-in functions such as int(), float(), and str(). This section focuses on converting data types explicitly to ensure proper data manipulation when automatic conversions are not available or suitable.

Integer to String Conversion

To combine numbers with strings or to output numbers as part of strings in display messages, you need to convert integers to strings. This is done using the str() function.

Example

Using str() to convert an integer to a string.

Python3
Python3

. . . .

Explanation:

  • num = 10 initializes an integer.
  • num_str = str(num) uses the str() function to convert the integer to a string.
  • print("String:", num_str) outputs the string representation of num.

String to Integer Conversion

When dealing with input or data that involves numerical values stored as strings, such as user inputs or data read from a file, you may need to convert these strings back to integers for mathematical operations. The int() function is used for this purpose.

Example

Converting a string to an integer using int().

Python3
Python3

. . . .

Explanation:

  • num_str = "20" defines a string that looks like a number.
  • num = int(num_str) converts the string to an integer using the int() function.
  • print("Integer:", num) shows the integer value, confirming the conversion.

Integer to Float Conversion

There are situations, especially in calculations involving division or precise measurements, where converting integers to floats is necessary. The float() function is used to convert integers (or other compatible types) to floating-point numbers.

Example

Converting an integer to a float using float().

Python3
Python3

. . . .

Explanation:

  • num_int = 4 sets up an integer.
  • num_float = float(num_int) converts the integer to a float, ensuring it has a decimal point.
  • print("Float:", num_float) shows the float value, illustrating that the integer has been converted to a float with a decimal.

Boolean to Integer Conversion

Booleans in Python can also be converted to integers for numerical computations where True is equivalent to 1 and False is 0.

Example

Converting booleans to integers.

Python3
Python3

. . . .

Explanation:

  • true_value = True and false_value = False set up Boolean variables.
  • true_int = int(true_value) and false_int = int(false_value) convert the booleans to their respective integer equivalents.
  • The print statements confirm the conversion results, showing 1 for True and 0 for False.

Data Type Conversion Functions

Python provides several built-in functions that allow explicit conversion between different data types. These functions are essential tools in Python programming, enabling manual data type conversions where automatic conversions are not appropriate or possible. Below is a table summarizing the main type conversion functions available in Python:

FunctionDescriptionExample Usage
int()Converts a number or string to an integer, if possible.int(2.8)2
float()Converts a number or string to a floating point number.float("3.5")3.5
str()Converts an object to a string representation.str(10)"10"
bool()Converts an object to a Boolean value, using standard truth testing.bool(0)False
complex()Converts a number or string to a complex number.complex(2, 3)2+3j
list()Converts an iterable to a list.list("abc")['a', 'b', 'c']
tuple()Converts an iterable to a tuple.tuple("abc")('a', 'b', 'c')
set()Converts an iterable to a set (removing duplicate elements).set("abac"){'a', 'b', 'c'}
dict()Creates a dictionary from a sequence of key-value pairs.dict([(1, 'one'), (2, 'two')]){1: 'one', 2: 'two'}
bin()Converts an integer to a binary string.bin(3)'0b11'
hex()Converts an integer to a hexadecimal string.hex(255)'0xff'
oct()Converts an integer to an octal string.oct(8)'0o10'

These functions are instrumental for ensuring that data types match expected formats in functions and operations, thereby preventing type errors and streamlining code execution.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next