Header Ads Widget

Ticker

6/random

Python Casting

Python Casting


Casting in Python refers to the process of converting one data type into another. Python provides several built-in functions for casting:

1. int()

Converts a number or a string containing a whole number into an integer.

   

```python

   x = int(3.14) # x will be 3

   y = int("5") # y will be 5

   ```

2. float(): 

Converts a number or a string containing a number into a floating-point number.

   

```python

   a = float(5) # a will be 5.0

   b = float("3.14") # b will be 3.14

   ```

3. str(): 

Converts any data type into a string.

   

```python

   name = "John"

   age = 25

   info = str(age) + " years old" # info will be "25 years old"

   ```

4. bool(): 

Converts a value into a Boolean (True or False).

  

```python

   x = bool(0) # x will be False

   y = bool(5) # y will be True

   ```

These examples showcase how to use casting functions to convert between different data types in Python. Keep in mind that not all types can be converted to each other, and errors may occur if the conversion is not possible.

Post a Comment

0 Comments