CH - 2 Variables and data types

Basics of variables, different data types, and how to use them

Variables

What is a variable?

In any programming language, a variable refers to the name given to a part of computer memory (RAM) to store a specific value.

In simpler terms, if you wish to store/remember a value in your program, you’ll use a variable.

A variable can store any value, from integers and strings to even user-defined, custom data (classes).

Why do we need variables?

Variables spare us from remembering the actual memory address of a value we’re storing. Without variables, we’d need to remember the address of each and every value we wish to store for our program

Variables can be made using the "=" operator, as seen in the following code snippet:

# Syntax for declaring a variable: <variable name> = <value to be stored>
num = 10
decimal = 2.3
name = "ACM"
guilty = True

# To access any value stored in our program, we only need to remember the variable name

print(num) # prints 10, since that was the value we stored

# We can always reassign variable values too
num = 100000
print(num) # prints 100000

Naming rules
Note: Names should be self-explanatory: Instead of naming variables as ‘x’, or ‘myvar’, it is important to name them something which can be understood intuitively.
# Good naming examples
playerHealth = 100 # Health of a player
employee_name = "Alexis" # Name of an employee


# Bad naming practices
x = True # What are we setting as True here? No clue

var = 313.16
# No clue what var is meant to represent, could be price, rating, percentage, we would never be able to guess

Data Types

A data type defines what kind of value a variable can store. Python supports various data types, and it’s important to understand these as they are the building blocks of programming.

Numeric Data Types

Boolean Data Type:

Strings:

We can use the type() function to get the data type of an operator

testStr = "123"
print(type(testStr)) 

testNum = 983
print(type(testNum))

print(type(3.14))