02-02: Variables and Data Types¶
What is a Variable?¶
A variable can be thought of as a label attached to a value.
It represents a named reference to data stored in memory, allowing that data to be accessed and modified throughout a program.
x refers to the integer value 10
name refers to the string value "Imran"
Rules for Naming Variables¶
✅ Valid Examples¶
❌ Invalid Examples¶
2age = 25 # cannot start with a number
user-name = 10 # hyphen not allowed
3 = num # not allowed, variable has to be on the left
_3 = 10 # legal, but not recommended
🔹 Naming Rules¶
- Only letters (a–z, A–Z), digits (0–9), and underscore (_) are allowed in variable names
- A variable name must begin with a letter or an underscore (_)
- A variable name cannot begin with a digit
- Spaces and special characters (except underscore) are not allowed
- Variable names are case-sensitive (age and Age are different)
Assigning Values to Variables¶
Values are assigned using the = operator.
- Python automatically determines the data type of the assigned value.
🔄 Multiple Assignment¶
- Multiple variables can be assigned values in a single statement.
- It is also possible to assign the same value to multiple variables:
Basic Data Types in Python¶
1️⃣ Integer (int)¶
Represents whole numbers.
2️⃣ Float (float)¶
Represents decimal numbers.
3️⃣ String (str)¶
Represents textual data enclosed in quotes.
4️⃣ Boolean (bool)¶
Represents logical values: True or False.
Checking Data Type¶
- The type() function is used to determine the data type of a variable.
👉 Output:
Type Conversion (Casting)¶
- Type conversion is used to convert a value from one data type to another.
Convert string to integer¶
Convert integer to float¶
Putting it together:
👉 Output:
⚠️ Important Notes: 🔹 Dynamic Typing¶
- Python is a dynamically typed language, meaning a variable can refer to different data types during execution.
👉 Output:
---¶
Exercises: 02-02: Exercises — Variables and Data Types
⬅️ Previous: 02-01: Basic Syntax ➡️ Next: 02-03: Input and Output