Lesson 7 of 4018%
(Progress persistence is disabled until Phase 9)
Python
Beginner
Type Conversion
Learn how to convert data from one type to another.
Type Conversion
What You’ll Learn
Sometimes you need to change the type of a variable. You’ll learn how to cast (convert) data from one type to another.
Basic Casting Functions
Python uses functions to cast values:
int()- constructs an integer number from an integer literal, a float literal, or a string literal.float()- constructs a float number from an integer literal, a float literal, or a string literal.str()- constructs a string from a wide variety of data types, including strings, integer literals and float literals.
Examples
To Integer
x = int(1) # x will be 1
y = int(2.8) # y will be 2 (decimals are removed)
z = int("3") # z will be 3
To Float
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
To String
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Common Mistakes
- Converting invalid strings: Trying to run
int("hello")will result in aValueError, because Python doesn’t know how to turn “hello” into a number.