Lesson explanation
After this lesson, you will be able to:
type() and avoid changing a variable's meaning carelessly.int() and float().Python variables are names that refer to values. You do not declare them with String, int, let, or const:
service_name = "billing-api"
worker_count = 6The value determines the current type, and type() lets you inspect it. A name can later refer to another type, but that flexibility should not make the code unpredictable. Reassign a variable when its value changes; use a new name when its meaning changes.
Configuration files, forms, and environment variables often provide numbers as text. Convert them before numeric work:
max_workers = int("8")
timeout_seconds = float("2.5")Python also supports multiple assignment. You can assign several values in one line or exchange two values without a temporary variable.
Use descriptive snake_case names such as request_timeout, not Java-style declarations or vague names such as x1.
💡 Tip:
int()accepts whole-number text such as"42". Usefloat()when the text may contain a decimal point.
Python infers the type from each value.
region = "eu-central"
replicas = 3
print(type(region))
print(type(replicas))Output:
<class 'str'>
<class 'int'>Convert external text before treating it as a number.
timeout_text = "1.75"
timeout_seconds = float(timeout_text)
print(f"Timeout: {timeout_seconds:.2f}s")Output:
Timeout: 1.75sReassignment keeps the same name and gives it a new value.
build_state = "queued"
build_state = "running"
print(f"State: {build_state}")Output:
State: runningPython can unpack values and exchange them in one statement.
primary_host, backup_host = "db-a", "db-b"
primary_host, backup_host = backup_host, primary_host
print(f"Primary: {primary_host}")
print(f"Backup: {backup_host}")Output:
Primary: db-b
Backup: db-aString name = ... or let count = ...."8" to behave like the number 8 until it is converted.Python for Developers
Assembled code
Generated code is hidden by default. Expand it only if you want to inspect what your current blank values produce.
0 / 4 tasks completed
| Goal | Python |
|---|
| Assign a value | name = value |
| Inspect the current type | type(value) |
| Convert whole-number text | int(text) |
| Convert decimal text | float(text) |
| Assign several values | a, b = value_a, value_b |
| Exchange two values | a, b = b, a |