This is a memorandum of learning Python. We hope that it will be helpful for beginners in programming and those who are also interested in other languages.
Before we explain type conversion, we need to explain the data type. A data type is a type of data handled by programming.
For example, the value (object) assigned to a variable determines the data type of this variable. In other words, what type of data is it, such as numbers and character strings?
In addition, there are various types of data types. So-called "character string type", "numeric type", etc. I will omit it this time because it seems to be quite long if I write it in detail.
And if this data type is different, the code behaves differently. Therefore, type conversion is required.
script.py
print(2 + 2) #Numerical calculation
#Execution result
4
print('2' + '2') #String concatenation
#Execution result
22
An error will occur if you concatenate the "character string type" and "numeric type" that are different data types.
script.py
price = 1000
print('The price of this book is' + price + 'It's a yen')
#The above is(String type+Numeric type+String type)Concatenation of different data types
#Execution result
#error:You cannot connect different types
TypeError: Can't convert 'int' object to str implicitly
However, if you convert from "numeric type" to "character string type" when outputting the variable price as shown below, it will be treated as a concatenation of character strings, so it will be possible to concatenate and change this data type. This is called "** type conversion **".
Use "** str () **" to convert "numeric type" to "character string type".
script.py
price = 1000
print('The price of this book is' + str(price) + 'It's a yen')
#The above is(String type+Convert to string type+String type)Can be connected next to
#Execution result
The price of this book is 1000 yen
Contrary to the previous, when converting "character string type" to "numeric type", use "** int () **".
script.py
price = 1000
count = '5' #String type
total_price = price * int(count) #Convert to numeric type
print(total_price)
#Execution result
5000
The content is really rudimentary, so I would like to write an article again when I proceed with my studies. Also, please do not hesitate to point out anything! !!
Recommended Posts