Chapter 2 - Data Types
Table of contents
Strings and Integers
Strings are the data type which are used to represent characters. They are shown in Python inside either double quotes (""
), or single quotes (''
). Integers are whole numbers, without the speech marks. Let's carry on from the statement in the previous chapter, one = 1
. If the statement would have been one = "1"
, the variable one
would have been a string, as it was in the speech marks, but since 1 wasn't in the speech marks, one
is an integer. A simple way to figure out if the variable is an integer or not is by using the function type()
. So write the the code print(type(one))
. If the output is <class 'int'>
, the variable is an integer. If the output is <class 'str'>
, the variable is a string. Other output mean other data types, but we will talk about that later. Now if you want to convert one
to a string, you have to do the code in the picture below.
onestring = str(one)
After you write that code and run it, one
will be equal to the integer 1
, but onestring
will be equal to "1"
.
If you ever come across the situation where you have to change a string to an integer, use int(name_of_variable)
. So if you want to convert onestring
to an integer, you could do oneinteger = int(onestring)
.
When you write an input statement, something like number = input("Enter a number")
, number is a string. But if you want number
to be an integer, you have to write the code below.
number = int(input("Enter a number"))
Then, number
will be an integer.
Floats
Floats are numbers that are made up of whole numbers and fractions, they are written in decimals. You can also assign a variable the value of a float. There is a also a function called float()
. It coverts the specified value in a floating point number. The function looks like float(name_of_variable)
. For example, if you want to check out the float of 4.600, you will have to do print(float(4.600))
. When you run the code, you will get the result of the picture below in the console.
Another example is checking the float of 9. To check it, you have to write the code print(float(9))
. After you run the code, you should get the result of '9.0'.
Thanks for reading and I hope you learnt something from this!
Top comments (2)
cool
thanks!