Hello! Last week I gave a brief introduction to the world of Python and this week I'm going to dive in a little deeper!
First I'm going to touch on the different data types found in Python and then focus on the Number and String data types. You can find the data type of any element by using the type() command. To see the data type printed out you would run this command in conjunction with the print command.
Here I set a variable to contain a string value. When I run the file in the terminal, this is what get's printed out.
Python has several different data type categories and some categories have different data types within the category. W3Schools tells us:
The data type is set whenever a value is assigned to any variable and you can change the type by assigning a different type to that variable.
The Number data type category consists of three different types: int, float, and complex. Int is short for integer and represents a positive or negative whole number and the length can be unlimited. Here is an example:
Now when I run the file in the terminal I get 'int' type back:
The 'float' Number type consists of a positive or negative number containing at least one decimal.
Now I get type 'float' back:
Another common data type found in Python and other languages is the String data type. A string can be formed by wrapping it in either single quotes or double-quotes. To form a multi-line string, three quotes are used and the line break output will correspond to the line breaks found in the code.
In Python, strings are considered arrays and each character is a single string. Similar to JavaScript, you can access a certain character in a string by wrapping the index number in square brackets and preceding that with the variable name.
You can find the length of a string by using the len() function.
Python also has a slice method which will return a section of a string back. To implement this method, you need to declare the string to be sliced and then wrap the starting index and stopping index in square brackets and these numbers need to be separated by a colon. The last index value will not be included in the return value.
Negative slicing can also be implemented by using negative numbers. When this is done, the slice starts at the end of the string.
This has been a brief introduction to some of the different data types of Python. Python uses a lot of the same data types as other programming languages, like Number and String, with some subtle differences. Thanks for reading!
Top comments (0)