Table of Contents
Variables in Python
In Python, a variable acts as a named storage location that holds a value. Unlike statically-typed languages, Python uses dynamic typing, meaning you don’t explicitly declare a variable’s type; it’s inferred at runtime based on the assigned value. This flexibility simplifies coding but requires careful attention to data types.
Creating Variables:
Variable creation involves assigning a value using the =
operator:
name = "Alice" # String
age = 30 # Integer
height = 5.8 # Float
is_adult = True # Boolean
Naming Conventions:
- Start with a letter (a-z, A-Z) or underscore (_).
- Contain letters, numbers (0-9), and underscores.
- Case-sensitive (
myVar
≠myvar
). - Use descriptive names (e.g.,
user_age
instead ofx
).
Fundamental Data Types
Python offers several built-in data types:
- Integers (
int
): Whole numbers (e.g., 10, -5, 0). - Floating-Point Numbers (
float
): Numbers with decimal points (e.g., 3.14, -2.5, 0.0). - Strings (
str
): Sequences of characters enclosed in single (‘ ‘) or double (” “) quotes (e.g., “Hello”, ‘Python’). Strings are immutable (cannot be changed in place). - Booleans (
bool
): Represent truth values:True
orFalse
. - NoneType (
None
): Represents the absence of a value.
Checking Data Types: Use the type()
function:
x = 10
print(type(x)) # Output: <class 'int'>
y = "Hello"
print(type(y)) # Output: <class 'str'>
Type Conversion and Casting
Converting between data types is often necessary. Python provides built-in functions for this:
str_num = "123"
int_num = int(str_num) # Convert string to integer
print(type(int_num)) # Output: <class 'int'>
float_num = 3.14
int_float = int(float_num) # Convert float to integer (truncates)
print(int_float) # Output: 3
int_to_str = str(10) # Convert integer to string
print(type(int_to_str)) # Output: <class 'str'>
Note that not all conversions are always possible (e.g., converting “abc” to an integer will raise a ValueError
).
This tutorial covered the fundamentals of variables and data types. Further learning involves exploring more advanced data structures like lists, tuples, dictionaries, and sets, which build upon these core concepts.