Python Basics: Understanding Variables and Data Types

Eric Lafforgue/Art in All of Us/GettyImages
facebooktwitterreddit

Python is one of the more popular languages right now, thanks to how easy it is to pick up and start using. It’s easy to read and is highly versatile. You can use it to train and work with intelligence(AI), control IoT devices, and much more. If you are starting with this amazing language, learning how to use variables and the different types of data in Python is critical for writing code.

What Are Variables?

Variables are placeholders for data in your code. The data can be a number, string, image, etc. As the name implies, this data often changes as the script runs, though it doesn’t have to.

How to Declare a Variable

To declare a variable in Python is easy. Choose a name for your variable and use the equals sign (=) to assign it a value.

Example Variable Declarations

name = "Alice"

age = 30

is_student = True

Understanding Data Types

Every piece of data in Python has a specific type, which determines what you can do with it. Though you don’t need to declare the type when you declare a new variable, as you do in many other programming languages, you need to be aware of them.

Integer (int)

Integers are whole numbers, positive or negative, that don’t have any decimal points.

number_of_coins = 10

Floating-Point Numbers (float)

Floats are numbers that can be positive or negative and have decimal points.

pi = 3.14159

String (str)

Strings are sequences of characters enclosed in single or double quotation marks. A string can contain a single character or an entire book of text.

First_word = “hello”

Booleans (bool)

Boolean values are true or false.

is_raining = False

List (list)

A list is an ordered collection of items enclosed in square brackets and is also commonly called an array. The data in a list can be integers, floats, or any other data.

fruits = [“apple”, “banana”, “cherry”]

Tuple (tuple)

Tuples are similar to lists, but they are immutable, which means you can’t change the values of the data after creating it.

Dictionaries (dict)

Dictionaries are collections of key-value pairs, where each key is unique and enclosed in curly braces.

Understanding variables and data types is the first step in becoming proficient in Python, and you will see them everywhere in your scripts.

Follow GeekSided to learn more about Python and to leave comments and questions.

feed