Tuesday, July 31, 2018

(Python) Python Data Types

In building a foundation for future entries on the topic of Python programming, we must first discuss the data types inherit within the Python programming language. I am aware that this is not the most riveting material, however, bear with me, as a strong understanding of the fundamental aspects is essential for later mastery of the subject.

Numbers

An integer, or an "int", is essentially a whole number. A float is a variable which possesses a decimal value. Unlike other programming languages, a numeric value does not need to be assigned a type when it is initially declared.

# integer #

a = 11

# float #

a = 11.11

Strings


A string is a non-numeric value. Typically a string is series of characters. For example, "This is a string", is a string type variable. However, like the example below, a string can also contain numerical values, such as, "1000". Strings receive a different treatment within the programming language, as compared to numeric variables. This will be demonstrated within future articles.

# string #

a = "11"


Lists

A list is a collection of elements. Lists are ordered and modifiable.

# list #

a = ["a"," b", "c","d"]

# list #

a =[1,2,3,4,5]

# list #

a = ["a","b","c",4,5]

# multi-dimensional list #

a = [["a", "b", "c"], [1, 2, 3]]


Tuple

A list is a collection of elements. Lists are ordered and un-modifiable.

# Fixed in size #

# tuple #

a = ('a', 'b', 'c', 'd', 'e')


Dictionary

A dictionary is a collection of elements which are unordered. It is modifiable and does not allow for duplicate entries.

# dictionary #

fruit = {'red': apple, 'green': pear}


Checking Data Types

To check a variable type within the python console, the following function can be utilized:

type()

# Example #

a = 4.44


print(type(a))

Which produces the output:

<class 'float'>

Changing Variable Types

There are few different options available as it pertains to modifying variable types. The utilization of such, depends on the type of variable that you would like to produce.

str() - To produce a string variable.

float() - To produce a float variable.

int() - To produce an integer variable.

# Example #

a = 4.44

# Modify the variable to a string variable type #

a = str(a)

print(type(a))

# Modify the variable to a float variable type #

a = float(a)

print(type(a))

# Modify the variable to an integer variable type #

a = int(a)

print(type(a))


In the next entry we will begin discussing some if the various options which are available for differing variable type. Stay Tuned!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.