1. Variables
A variable is a name that refers to a value stored in memory. Variables are used to store data that can be referenced and manipulated throughout your program.
Declaring Variables
- Variables are created when you assign a value to them.
x = 10 # Integer name = "Alice" # String pi = 3.14 # Float
- Python allows you to assign multiple variables in one line:
a, b, c = 1, 2, 3
Rules for Naming Variables
- Variable names must start with a letter or an underscore (
_
). - Names can only contain letters, numbers, and underscores (e.g.,
var_name1
). - Python is case-sensitive (
name
andName
are different). - Avoid using Python reserved keywords (e.g.,
if
,while
,def
, etc.).
2. Data Types
Python is a dynamically-typed language, meaning you don’t need to specify the type of a variable—it is inferred from the assigned value.
Common Data Types in Python
- Numeric Types
- Integer (
int
): Whole numbers.age = 25
- Floating-Point (
float
): Numbers with decimal points.price = 19.99
- Complex (
complex
): Numbers with real and imaginary parts.z = 3 + 4j
- Integer (
- String (
str
)- A sequence of characters enclosed in single or double quotes.
greeting = "Hello, World!"
- Supports operations like slicing and concatenation:
name = "Alice" print(name[0]) # Output: A print(name[1:4]) # Output: lic
- A sequence of characters enclosed in single or double quotes.
- Boolean (
bool
)- Represents
True
orFalse
values.is_logged_in = True
- Represents
- Sequence Types
- List (
list
): Ordered, mutable collection of items.numbers = [1, 2, 3, 4]
- Tuple (
tuple
): Ordered, immutable collection.point = (1, 2)
- List (
- Dictionary (
dict
)- A collection of key-value pairs.
person = {"name": "Alice", "age": 25}
- A collection of key-value pairs.
- Set (
set
)- Unordered, unique collection of items.
fruits = {"apple", "banana", "cherry"}
- Unordered, unique collection of items.
3. Type Checking and Conversion
- Check Data Type
Use thetype()
function to find the type of a variable.x = 10 print(type(x)) # Output: <class 'int'>
- Type Conversion
Convert between types using functions likeint()
,float()
,str()
, etc.x = 5.5 y = int(x) # Converts float to int (y = 5) z = str(x) # Converts float to string (z = "5.5")
By understanding variables and data types, you can effectively store, manipulate, and work with different kinds of data in Python.
One response
appreciate this content