Chapter 2: Python Basics - Data Types and Variables
Understand Python's fundamental data types and how to work with variables. Explore numeric, string, and boolean types for building blocks of your code.
In this chapter, we�ll cover essential data types and how variables function in Python. By the end, you�ll know how to declare and use different data types as the building blocks of your programs.
What is a Variable?
A variable in Python is a symbolic name associated with a value. Variables allow you to store and manipulate data throughout your code. Python is dynamically typed, so you don�t need to specify a variable�s data type explicitly.
Data Types in Python
Python supports several built-in data types that are essential for handling different kinds of information. Here are some of the primary data types:
1. Numeric Data Types
Python has three main numeric types:
- int: Used for whole numbers (e.g.,
10
,-5
). - float: Used for decimal numbers (e.g.,
3.14
,-2.0
). - complex: Used for complex numbers (e.g.,
1+2j
).
x = 10 # int
y = 3.14 # float
z = 1 + 2j # complex
2. String Data Type
Strings represent text in Python and are defined by enclosing characters in single ('
) or double ("
) quotes.
name = "Alice"
greeting = 'Hello, World!'
Strings can also be manipulated with various methods, such as upper()
for capitalization, or replace()
to substitute characters.
3. Boolean Data Type
Booleans represent two values: True
and False
. They are often used in conditional expressions to control program flow.
is_active = True
is_admin = False
Working with Variables
In Python, assigning a value to a variable is as simple as using the =
operator. Python automatically determines the type based on the value assigned. Variable names should be descriptive and follow best practices (e.g., snake_case).
age = 25
temperature = 36.6
username = "PythonUser"
Type Checking and Type Conversion
You can check the type of a variable using the type()
function and convert data types using functions like int()
, float()
, and str()
.
age = "25" # age is initially a string
age = int(age) # now age is an integer
temperature = 98.6
temperature = int(temperature) # converts to integer (98)
Summary and Next Steps
In this chapter, we covered Python�s basic data types and how to work with variables. You should now be comfortable declaring variables and understanding different data types in Python. In the next chapter, we�ll explore Python�s operators and how to use them in expressions.