Geek Slack

Introduction to Python
    About Lesson



    Python Casting


    Python Casting

    Casting in Python is the process of converting one data type to another. Python provides several built-in functions for casting data types, such as int(), float(), str(), list(), tuple(), and dict().

    1. Casting to Integer

    To convert a value to an integer, you can use the int() function.

    Example:

    x = int(3.14)
    y = int("5")

    2. Casting to Float

    To convert a value to a float, you can use the float() function.

    Example:

    x = float(5)
    y = float("3.14")

    3. Casting to String

    To convert a value to a string, you can use the str() function.

    Example:

    x = str(10)
    y = str(3.14)

    4. Casting to List

    To convert a value to a list, you can use the list() function.

    Example:

    x = list("hello")
    y = list((1, 2, 3))

    5. Casting to Tuple

    To convert a value to a tuple, you can use the tuple() function.

    Example:

    x = tuple([1, 2, 3])
    y = tuple("world")

    6. Casting to Dictionary

    To convert a value to a dictionary, you can use the dict() function.

    Example:

    x = dict(name="Alice", age=30)
    y = dict([('name', 'Bob'), ('age', 25)])

    Conclusion

    Casting allows you to convert data from one type to another in Python. Understanding how to use casting functions is essential for working with different data types and ensuring compatibility in your Python programs.