Variables and Basic Data Types
8 min ยท The Basics
What are Variables?
Variables are containers for storing data values in your program. Think of them as labeled boxes where you can put different types of information. Variables allow you to store data, reuse it, and manipulate it throughout your program.
In Python, creating a variable is simple - you just assign a value to a name using the = operator. Python automatically determines the type based on the value you assign.
Basic Data Types
Python has several built-in data types. Understanding these types is fundamental to programming in Python:
str(String) โ Text data enclosed in quotes:"Hello",'Python',"""Multi-line"""int(Integer) โ Whole numbers:42,-7,1000,0float(Floating Point) โ Decimal numbers:3.14,-0.5,2.0bool(Boolean) โ Logical values:TrueorFalse(must be capitalized)Noneโ Represents the absence of a value (similar to null in other languages)
Working with Strings
Strings can be created with single, double, or triple quotes. Triple quotes allow multi-line strings:
Working with Numbers
Python supports both integers and floating-point numbers. Here are some important points:
Working with Booleans
Boolean values represent truth. They're essential for control flow and logic:
Checking Types
Use the type() function to check what type a variable is. This is useful for debugging and understanding your data:
Variable Assignment and Reassignment
Variables in Python can be reassigned to new values at any time. The variable doesn't have a fixed type - it can hold different types of values:
Variable Naming Rules
Python has specific rules for variable names. Following these rules ensures your code works correctly:
๐ Naming Rules
โข Must start with a letter (a-z, A-Z) or underscore (_)
โข Can contain letters, numbers, and underscores
โข Cannot start with a number
โข Case-sensitive: name and Name are different
โข Cannot use Python keywords (if, for, def, etc.)
โข Use snake_case (lowercase with underscores) by convention
Best Practices for Variable Names
โ Good Variable Names
Use descriptive names that explain what the variable stores: user_age, total_price, is_logged_in
โ Avoid These
Don't use single letters (except in loops) or abbreviations: x, temp, usr - these make code hard to understand!
Using Variables in Expressions
Variables can be used in calculations and expressions. The variable's current value is used: