Python Basics- Variables and Data Types
Python Basics- Variables and Data Types
This file introduces fundamental concepts in Python: variables and common data types.
1. Variables:
- Variables are used to store data values.
- You assign a value to a variable using the assignment operator (`=`).
- Variable names are case-sensitive and should follow certain rules (e.g., start with a letter
or underscore, contain only alphanumeric characters and underscores).
- Example:
```python
name = "Alice"
age = 30
is_student = False
pi = 3.14159
```
2. Data Types:
- Python has several built-in data types that represent different kinds of values.
- **int:** Represents whole numbers (e.g., 10, -5, 0).
```python
count = 100
```
- **float:** Represents floating-point numbers (numbers with a decimal point) (e.g., 3.14,
-0.5, 2.0).
```python
price = 9.99
temperature = 25.5
```
- **str:** Represents sequences of characters (text) enclosed in single or double quotes
(e.g., "hello", 'world').
```python
message = "Hello, Python!"
city = 'Dublin'
```
- **bool:** Represents boolean values, which can be either `True` or `False`. Often used for
logical operations.
```python
is_valid = True
has_permission = False
```
- **list:** Represents ordered, mutable sequences of items enclosed in square brackets `[]`.
Items can be of different data types.
```python
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True]
```
- **tuple:** Represents ordered, immutable sequences of items enclosed in parentheses
`()`. Once created, their elements cannot be changed.
```python
coordinates = (10, 20)
colors = ("red", "green", "blue")
```
- **dict:** Represents unordered collections of key-value pairs enclosed in curly braces `{}`.
Keys must be unique and immutable, while values can be of any type.
```python
person = {"name": "Bob", "age": 25, "city": "Cork"}
config = {"timeout": 30, "retries": 3}
```
Understanding variables and data types is the foundation of writing any Python program,
allowing you to store and manipulate different kinds of information.