Variables and Data Types

Storing Information: Variables and Data Types

Variables are the fundamental building blocks for storing data in any programming language. Think of them as labeled boxes where you can keep information to use later. Python is dynamically typed, which means you don't have to specify the data type of a variable; the interpreter figures it out automatically.

Variables

You create a variable by assigning a value to it using the equals sign =.

# Assigning a string to the variable 'name'
name = "Alice"
# Assigning an integer to the variable 'age'
age = 30
# You can print variables to see their values
print(name)
print(age)
        

Core Data Types

Python has several built-in data types to represent different kinds of information:

  • String (str): Used for text. Enclosed in single ('') or double ("") quotes. Example: "Hello, Python!"
  • Integer (int): Used for whole numbers. Example: 100, -5
  • Float (float): Used for numbers with decimal points. Example: 3.14, -0.01
  • Boolean (bool): Represents one of two values: True or False. Crucial for control flow.

Type Casting

Sometimes you need to convert a variable from one data type to another. This is called type casting.

# A number stored as a string
age_string = "25"
print("Age as a string:", age_string)

Convert the string to an integer

age_integer = int(age_string) print("Age as an integer:", age_integer)

You can now do math with the integer

next_year_age = age_integer + 1 print("Next year you will be:", next_year_age)

Checking the Type

You can use the type() function to find out the data type of any variable.