|
| 1 | +--- |
| 2 | +id: python-casting |
| 3 | +title: Type Casting |
| 4 | +sidebar_label: Type Casting #displays in sidebar |
| 5 | +sidebar_position: 6 |
| 6 | +tags: |
| 7 | + [ |
| 8 | + Python, |
| 9 | + Introduction of python, |
| 10 | + Python Syntax, |
| 11 | + Python Variables, |
| 12 | + Python Operators, |
| 13 | + Type Casting, |
| 14 | + |
| 15 | + ] |
| 16 | + |
| 17 | +--- |
| 18 | + |
| 19 | +# Python Casting |
| 20 | + |
| 21 | +In Python, **casting** is the process of converting a variable from one type to another. |
| 22 | +Python has built-in functions for converting between data types. |
| 23 | + |
| 24 | +--- |
| 25 | + |
| 26 | +### Specify a Variable Type |
| 27 | + |
| 28 | +Python is an **object-oriented language**, and **variables are objects**. |
| 29 | +You can specify the data type using casting functions: |
| 30 | + |
| 31 | +```python |
| 32 | +x = int(1) # x will be 1 |
| 33 | +y = int(2.8) # y will be 2 |
| 34 | +z = int("3") # z will be 3 |
| 35 | +```` |
| 36 | + |
| 37 | + |
| 38 | +### `int()` - Integer Casting |
| 39 | + |
| 40 | +Converts a value to an integer. Works with floats and numeric strings. |
| 41 | + |
| 42 | +```python |
| 43 | +x = int(1) # 1 |
| 44 | +y = int(2.8) # 2 |
| 45 | +z = int("3") # 3 |
| 46 | +# w = int("abc") # ❌ Error |
| 47 | +``` |
| 48 | + |
| 49 | + |
| 50 | +### `float()` - Floating-Point Casting |
| 51 | + |
| 52 | +Converts a value to a float. Works with integers and numeric strings. |
| 53 | + |
| 54 | +```python |
| 55 | +a = float(1) # 1.0 |
| 56 | +b = float("2.5") # 2.5 |
| 57 | +c = float(3.0) # 3.0 |
| 58 | +``` |
| 59 | + |
| 60 | + |
| 61 | +### `str()` - String Casting |
| 62 | + |
| 63 | +Converts numbers or other types into a string. |
| 64 | + |
| 65 | +```python |
| 66 | +x = str("s1") # 's1' |
| 67 | +y = str(2) # '2' |
| 68 | +z = str(3.0) # '3.0' |
| 69 | +``` |
| 70 | + |
| 71 | +### Invalid Casting |
| 72 | + |
| 73 | +Some values can't be casted directly: |
| 74 | + |
| 75 | +```python |
| 76 | +int("hello") # ValueError |
| 77 | +float("abc") # ValueError |
| 78 | +``` |
| 79 | + |
| 80 | +Use `try`/`except` to handle safely: |
| 81 | + |
| 82 | +```python |
| 83 | +value = "abc" |
| 84 | +try: |
| 85 | + number = int(value) |
| 86 | +except ValueError: |
| 87 | + print("Invalid conversion") |
| 88 | +``` |
| 89 | + |
| 90 | +### Summary Table |
| 91 | + |
| 92 | +| Function | Converts to | Example Input | Output | |
| 93 | +| --------- | ----------- | ------------- | ------- | |
| 94 | +| `int()` | Integer | `"3"` | `3` | |
| 95 | +| `float()` | Float | `"3.5"` | `3.5` | |
| 96 | +| `str()` | String | `3.5` | `"3.5"` | |
| 97 | + |
| 98 | + |
| 99 | +### Quick Notes |
| 100 | + |
| 101 | +* Use casting to convert types manually. |
| 102 | +* Useful when handling user input, math, or data from files. |
| 103 | +* Always validate input before casting to avoid errors. |
0 commit comments