Data Types, Typecasting, eval(), Boolean Logic & String Formatting
Today, we explored Python’s fundamental and derived data types, typecasting, boolean truthiness, input/output operations, and string formatting. While these topics may seem basic, they’re the foundation of every DevOps automation script you’ll write.
A surprising realization from today’s session was that AWS API responses, Kubernetes objects, Terraform outputs, and JSON payloads all map directly to Python data structures. Understanding these types is not just about learning Python—it’s about understanding how automation tools communicate.
Python Data Types Overview
Python data types can broadly be divided into two categories:
Fundamental Types Collection Types int list float tuple complex set str dict bool NoneFundamental Data Types
Integer (int)
Integers represent whole numbers and, unlike many programming languages, Python doesn’t impose a practical size limit on them.
port = 22
replicas = 3
exit_code = 0
big_number = 9237093793579275093270937509750937095709327509327095737509375375093275093275
Enter fullscreen mode Exit fullscreen mode
This makes Python particularly convenient when dealing with very large numerical values.
Float (float)
Floats store decimal numbers and are commonly used for thresholds, percentages, prices, and time-related values.
cpu_threshold = 85.5
spot_price = 0.012
disk_usage = 73.6
Enter fullscreen mode Exit fullscreen mode
One thing worth remembering is that Python automatically removes trailing zeros.
10.00
Enter fullscreen mode Exit fullscreen mode
becomes:
10.0
Enter fullscreen mode Exit fullscreen mode
Complex (complex)
Complex numbers are rarely used in DevOps but are supported natively by Python.
a = 3 + 4j
print(a.real)
print(a.imag)
Enter fullscreen mode Exit fullscreen mode
Output:
3.0
4.0
Enter fullscreen mode Exit fullscreen mode
String (str)
Strings represent textual data and can be written using single, double, or triple quotes.
env = 'production'
message = "It's a healthy instance"
terraform_block = '''
resource "aws_instance" "web" {
ami = "ami-0abcdef1234"
instance_type = "t2.micro"
}
'''
Enter fullscreen mode Exit fullscreen mode
A common mistake:
msg = 'It's broken'
Enter fullscreen mode Exit fullscreen mode
This causes a syntax error because the apostrophe terminates the string.
Correct approaches:
msg = "It's fixed"
msg = 'It's fixed'
Enter fullscreen mode Exit fullscreen mode
Boolean (bool)
Booleans contain only two possible values.
is_healthy = True
is_scaling = False
Enter fullscreen mode Exit fullscreen mode
Python is case-sensitive:
true
TRUE
Enter fullscreen mode Exit fullscreen mode
Both are invalid.
Only:
True
False
Enter fullscreen mode Exit fullscreen mode
are valid boolean values.
None
None represents the absence of a value.
response = None
instance_id = None
if response is None:
print("No response from AWS API")
Enter fullscreen mode Exit fullscreen mode
This pattern appears frequently when handling API calls and optional values.
Collection Data Types
These data structures become extremely important when working with cloud services and automation tools.
List
Lists are ordered, mutable, and allow duplicate values.
servers = ['web-01', 'web-02', 'db-01']
print(servers[0])
servers[0] = 'web-03'
Enter fullscreen mode Exit fullscreen mode
Lists are heavily used for storing groups of resources such as servers, ports, buckets, or security groups.
ports = [22, 80, 443, 8080]
Enter fullscreen mode Exit fullscreen mode
Tuple
Tuples are ordered and immutable.
aws_regions = (
'us-east-1',
'ap-south-1',
'eu-west-1'
)
Enter fullscreen mode Exit fullscreen mode
Attempting to modify a tuple results in an error.
aws_regions[0] = 'us-west-2'
Enter fullscreen mode Exit fullscreen mode
This makes tuples useful for constants that should never change.
Set
Sets automatically remove duplicates.
unique_ips = {1, 2, 3, 3, 2, 1}
print(unique_ips)
Enter fullscreen mode Exit fullscreen mode
Output:
{1, 2, 3}
Enter fullscreen mode Exit fullscreen mode
A practical DevOps example:
raw_logs = {
'10.0.0.1',
'10.0.0.2',
'10.0.0.1',
'10.0.0.3'
}
Enter fullscreen mode Exit fullscreen mode
Sets are excellent for deduplicating IP addresses and resource identifiers.
Dictionary
Dictionaries store key-value pairs and are arguably the most important data structure for cloud engineers.
instance = {
'instance_id': 'i-0abc123',
'type': 't2.micro',
'region': 'ap-south-1',
'status': 'running'
}
Enter fullscreen mode Exit fullscreen mode
Accessing values:
print(instance['status'])
Enter fullscreen mode Exit fullscreen mode
One key reason dictionaries matter:
AWS API responses, JSON payloads, Kubernetes objects, and Terraform outputs all map naturally to dictionaries.
Example:
ec2_instance = {
'InstanceId': 'i-0abc123def456',
'InstanceType': 't3.micro',
'State': {'Name': 'running'},
'PublicIpAddress': '13.234.56.78'
}
print(
ec2_instance['State']['Name']
)
Enter fullscreen mode Exit fullscreen mode
Typecasting
Typecasting converts one data type into another.
This becomes necessary because user input, environment variables, and many API values arrive as strings.
int('10')
float('10.5')
str(8080)
Enter fullscreen mode Exit fullscreen mode
A common mistake:
int('10.5')
Enter fullscreen mode Exit fullscreen mode
This raises:
ValueError
Enter fullscreen mode Exit fullscreen mode
The correct approach:
int(float('10.5'))
Enter fullscreen mode Exit fullscreen mode
Another important behavior:
int(38.99)
Enter fullscreen mode Exit fullscreen mode
returns:
38
Enter fullscreen mode Exit fullscreen mode
because int() truncates rather than rounds.
Boolean Truthiness
Python automatically evaluates values as either truthy or falsy.
Falsy values include:
0
0.0
''
None
[]
{}
()
set()
Enter fullscreen mode Exit fullscreen mode
Examples:
bool(0)
# False
bool('')
# False
bool(' ')
# True
bool(None)
# False
Enter fullscreen mode Exit fullscreen mode
A space character is not an empty string, which is why it evaluates to True.
Understanding eval()
The eval() function evaluates a string as Python code.
eval('1837')
eval('1837.63')
eval('True')
Enter fullscreen mode Exit fullscreen mode
One benefit is automatic type detection.
x = eval(input())
Enter fullscreen mode Exit fullscreen mode
However, using eval() with user input is dangerous.
eval(input())
Enter fullscreen mode Exit fullscreen mode
can potentially execute arbitrary code.
For production automation scripts, explicit casting is always safer.
int()
float()
Enter fullscreen mode Exit fullscreen mode
Input and Output
One of the most important beginner lessons:
input()always returns a string.
port = input("Enter port: ")
print(type(port))
Enter fullscreen mode Exit fullscreen mode
Output:
<class 'str'>
Enter fullscreen mode Exit fullscreen mode
Therefore:
port = int(
input("Enter port: ")
)
Enter fullscreen mode Exit fullscreen mode
is often required.
Python’s print() function also supports formatting options:
print(
"Python",
"DevOps",
"AWS",
sep=" | "
)
Enter fullscreen mode Exit fullscreen mode
print(
"Building",
end=" --> "
)
Enter fullscreen mode Exit fullscreen mode
String Formatting
Python supports multiple formatting styles.
String concatenation:
'Server is in ' + name
Enter fullscreen mode Exit fullscreen mode
Using .format():
'Server is in {}'.format(name)
Enter fullscreen mode Exit fullscreen mode
Using f-strings:
f'Server is in {name}'
Enter fullscreen mode Exit fullscreen mode
F-strings are the preferred modern approach.
service = "nginx"
status_code = 200
print(
f"[INFO] {service} | Status: {status_code}"
)
Enter fullscreen mode Exit fullscreen mode
DevOps Takeaway
The biggest insight from today’s class was understanding that Python data structures are the language through which cloud services communicate.
An AWS API response is a dictionary.
A list of instances is a list.
A collection of unique IP addresses is a set.
Configuration constants fit naturally into tuples.
Environment variables arrive as strings and often require typecasting.
These concepts may seem simple initially, but they form the foundation of every automation script, cloud SDK interaction, and infrastructure workflow you’ll build as a DevOps engineer.
답글 남기기