You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/python/python-casting.md
+11-80Lines changed: 11 additions & 80 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -6,97 +6,28 @@ sidebar_position: 6
6
6
tags:
7
7
[
8
8
Python,
9
-
Introduction of python,
10
-
Python Syntax,
11
-
Python Variables,
12
-
Python Operators,
13
9
Type Casting,
14
-
10
+
Type Conversion,
11
+
Python Data Types,
12
+
int(),
13
+
float(),
14
+
str(),
15
15
]
16
-
16
+
description: Learn how to convert a variable from one data type to another in Python using the built-in int(), float(), and str() functions.
17
17
---
18
18
19
19
# Python Casting
20
20
21
-
In Python, **casting** is the process of converting a variable from one type to another. Python has built-in functions for converting between data types.
21
+
In Python, **casting** is the process of converting a variable from one data type to another. Python has built-in functions for converting between data types.
22
22
23
23
---
24
24
25
-
### Specify a Variable Type
26
-
27
-
Python is an **object-oriented language**, and **variables are objects**.
28
-
You can specify the data type using casting functions:
29
-
30
-
```python
31
-
x =int(1) # x will be 1
32
-
y =int(2.8) # y will be 2
33
-
z =int("3") # z will be 3
34
-
````
35
-
25
+
## `int()` - Integer Casting
36
26
37
-
### `int()` - Integer Casting
38
-
39
-
Converts a value to an integer. Works with floats and numeric strings.
27
+
Converts a value to an integer. This function truncates floats (it does not round) and works with numeric strings.
40
28
41
29
```python
42
30
x =int(1) # 1
43
-
y =int(2.8) # 2
31
+
y =int(2.8) # 2 (value is truncated)
44
32
z =int("3") # 3
45
-
# w = int("abc") # Error
46
-
```
47
-
48
-
49
-
### `float()` - Floating-Point Casting
50
-
51
-
Converts a value to a float. Works with integers and numeric strings.
52
-
53
-
```python
54
-
a =float(1) # 1.0
55
-
b =float("2.5") # 2.5
56
-
c =float(3.0) # 3.0
57
-
```
58
-
59
-
60
-
### `str()` - String Casting
61
-
62
-
Converts numbers or other types into a string.
63
-
64
-
```python
65
-
x =str("s1") # 's1'
66
-
y =str(2) # '2'
67
-
z =str(3.0) # '3.0'
68
-
```
69
-
70
-
### Invalid Casting
71
-
72
-
Some values can't be casted directly:
73
-
74
-
```python
75
-
int("hello") # ValueError
76
-
float("abc") # ValueError
77
-
```
78
-
79
-
Use `try`/`except` to handle safely:
80
-
81
-
```python
82
-
value ="abc"
83
-
try:
84
-
number =int(value)
85
-
exceptValueError:
86
-
print("Invalid conversion")
87
-
```
88
-
89
-
### Summary Table
90
-
91
-
| Function | Converts to | Example Input | Output |
0 commit comments