Python data types

PythonThere are several built-in types.

If you createnameAssign the value "Roger" to the variable, this variable now automatically represents aStringtype of data.

name = "Roger"

you can use ittype()Function, pass the variable as a parameter, and then combine the result withstr:

name = "Roger"
type(name) == str #True

Or useisinstance():

name = "Roger"
isinstance(name, str) #True

Please note that you seeTrueValue in Python outside of the REPL, you need to wrap this code in itprint(), But for clear reasons, I avoid using it

We usedstrThe class is here, but other data types can also be used.

First, we have numbers. For integersintclass. Floating point numbers (fractions) are typesfloat:

age = 1
type(age) == int #True
fraction = 0.1
type(fraction) == float #True

You learned how to create a type from value literals, as follows:

name = "Flavio"
age = 20

Python automatically detects the type from the value type.

You can also create a specific type of variable by using the class constructor, and pass the value literal or variable name:

name = str("Flavio")
anotherName = str(name)

You can also use the class constructor to convert one type to another. Python will try to determine the correct value, such as extracting a number from a string:

age = int("20")
print(age) #20

fraction = 0.1 intFraction = int(fraction) print(intFraction) #0

This is calledcasting. Of course, depending on the value passed, this conversion may not always work. If you writetestinstead20In the above string, you will get aValueError: invalid literal for int() with base 10: 'test'error.

These are just the basis of the type. We have more types in Python:

  • complexFor complex numbers
  • boolFor Boolean
  • listFor the list
  • tupleFor tuples
  • rangeFor the range
  • dictFor the dictionary
  • setSuit

And more!

We will explore it as soon as possible.

More python tutorials: