DEV Community

Cover image for Python Basics β€” `print()`, Variables, Identifiers, Data Types
Tejas Shinkar
Tejas Shinkar

Posted on

Python Basics β€” `print()`, Variables, Identifiers, Data Types

πŸ“Œ Key Concepts

Concept One-Line Definition
print() Built-in function to output data to the terminal
Variable A named container in memory that holds a value
Dynamic Typing Python figures out the data type automatically at runtime
Identifier The name you give to a variable, function, or class
Keyword Reserved words Python uses internally β€” cannot be used as identifiers
type() Built-in function that tells you the data type of a value
id() Returns the memory address of an object

πŸ”€ Syntax

# print() β€” basic output
print("Hello DevOps")
print(variable_name)
print(value, type(value))   # print value AND its type together

# Variable assignment
port = 8080                  # int
service_name = "nginx"       # str
cpu_threshold = 85.5         # float

# type() β€” check data type
print(type(port))            # <class 'int'>

# id() β€” check memory address
print(id(service_name))

# keyword list
import keyword
print(keyword.kwlist)

# input() β€” take user input
name = input("Enter your name: ")
print("Hello", name)
Enter fullscreen mode Exit fullscreen mode

πŸ” Core Concepts Explained

1. print() Function

The most basic output function. In DevOps scripts, you'll use it constantly to log statuses, debug values, and show results.

print("Deployment started")
print("Server IP:", server_ip)
print("Status:", status, "| Code:", code)   # multiple values with comma
Enter fullscreen mode Exit fullscreen mode

2. Variables

A variable is just a label pointing to a value in memory. Think of it like naming a config value so you can reuse it.

# BAD β€” hardcoded everywhere
# connect("192.168.1.10", 22)
# connect("192.168.1.10", 22)

# GOOD β€” use a variable
server_ip = "192.168.1.10"
ssh_port = 22
connect(server_ip, ssh_port)
Enter fullscreen mode Exit fullscreen mode

3. Dynamic Typing

Python doesn't require you to declare the type. It detects it automatically. The same variable can hold different types at different times.

a = 10         # int
a = "hello"    # now str β€” Python is fine with this
a = 3.14       # now float
Enter fullscreen mode Exit fullscreen mode

⚠️ Common Mistake: Reassigning a variable to a different type accidentally can cause bugs in automation scripts.

4. Data Types (from class)

Type Example DevOps Use Case
int port = 22 Port numbers, exit codes
float cpu = 85.5 CPU/memory thresholds
str env = "prod" Environment names, server IPs
bool is_healthy = True Health check flags
port = 22              # int
threshold = 85.5       # float
environment = "prod"   # str
is_active = True       # bool
Enter fullscreen mode Exit fullscreen mode

5. Identifiers β€” Naming Rules

βœ… VALID          ❌ INVALID
server_ip         5server       (starts with number)
_private          server-ip     (hyphen = minus operator)
cpu2core          server ip     (space not allowed)
myVar             if            (reserved keyword)
EC2Instance       print = 100   (shadows built-in β€” avoid!)
Enter fullscreen mode Exit fullscreen mode

Golden Rule for DevOps Scripts: Use snake_case (lowercase with underscores) β€” server_ip, max_retries, aws_region. This matches Python convention and is easy to read.

6. Keywords β€” Off-Limits Names

import keyword
print(keyword.kwlist)
# ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
#  'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
#  'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
#  'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return',
#  'try', 'while', 'with', 'yield']
Enter fullscreen mode Exit fullscreen mode

7. Don't Shadow Built-ins ⚠️

The class demonstrated this critical mistake:

# ❌ NEVER do this
print = 100         # You just killed the print function!
print("Python")     # TypeError: 'int' object is not callable

# βœ… Restart kernel or use del to recover
del print
print("Python")     # Works again
Enter fullscreen mode Exit fullscreen mode

Common built-ins to never overwrite: print, input, list, dict, str, int, len, open, type, id


☁️ DevOps / Cloud Use Cases

# AWS EC2 config variables
instance_type = "t2.micro"
region = "ap-south-1"          # Mumbai
ami_id = "ami-0abcdef1234567890"
max_instances = 5
spot_price = 0.012             # float β€” price in USD

# Docker/K8s config
container_port = 8080
replica_count = 3
image_tag = "nginx:1.25"
is_rolling_update = True

# CI/CD pipeline variable
build_status = "SUCCESS"
exit_code = 0                  # 0 = success in Linux/bash
artifact_size_mb = 145.7

# Log line output (you'll do this in every script)
print(f"Deploying {image_tag} to {region} with {replica_count} replicas")
print(f"Build: {build_status} | Exit Code: {exit_code}")
Enter fullscreen mode Exit fullscreen mode

❌ Common Mistakes (from class + real world)

Mistake Example Fix
Typo in function name prin("Python") Check spelling β€” Python gives NameError
Shadow a built-in print = 100 Never use built-in names as variables
Use keywords as names if = 5 Use keyword.kwlist to check
Start var with number 5server = "aws" Start with letter or underscore
Space in variable name server ip = "x" Use server_ip
Wrong case Print("hi") Python is case-sensitive β€” print β‰  Print

🎯 Interview Points

  1. "Is Python statically or dynamically typed?"
    β†’ Dynamically typed. Types are determined at runtime, not declared. Use type() to check.

  2. "What's the difference between = and == in Python?"
    β†’ = assigns a value. == compares two values. Critical distinction in if conditions.

  3. "What is id() used for?"
    β†’ Returns memory address. Useful to understand if two variables point to the same object in memory.

  4. "Can a variable name start with a number?"
    β†’ No. It can start with a letter (A-Z, a-z) or underscore _.

  5. "What happens if you name a variable list or print?"
    β†’ You shadow the built-in. The original function becomes inaccessible in that scope β€” a common bug.

  6. "What is dynamic typing and why does it matter in DevOps scripts?"
    β†’ Python auto-detects types, so you must be careful when reading user input or config values β€” they come in as str by default, even if they look like numbers.


πŸ“š Knowledge Base (Quick Revision)

# ── PRINT ──────────────────────────────────────────
print("text")                    # basic
print(var, type(var))            # value + type
print("Label:", value)           # label + value

# ── VARIABLES & TYPES ──────────────────────────────
x = 10                           # int
x = 3.14                         # float
x = "hello"                      # str
x = True                         # bool

# ── USEFUL BUILT-INS ───────────────────────────────
type(x)                          # what type is x?
id(x)                            # memory address of x
input("Enter: ")                 # get user input (returns str)

# ── KEYWORDS ───────────────────────────────────────
import keyword
keyword.kwlist                   # list of all reserved words

# ── IDENTIFIER RULES ───────────────────────────────
# βœ… letters, digits (not first), underscore
# ❌ spaces, hyphens, special chars, keywords, starts with digit

# ── BUILT-IN SAFETY ────────────────────────────────
dir(__builtins__)                # list ALL built-in names
# Never use these as variable names!
Enter fullscreen mode Exit fullscreen mode

πŸ‹οΈ Practice Questions

Easy

  1. Write a Python script that stores your name, age, and city in variables and prints them with their data types.
  2. Try assigning if = 10 and run it. What error do you get? Now look up keyword.kwlist and list 5 keywords you didn't know.
  3. What is the output of this code? Explain why:
   a = "8080"
   print(a, type(a))
Enter fullscreen mode Exit fullscreen mode

Medium

  1. Create variables for: EC2 instance type, region, number of replicas, and whether auto-scaling is enabled. Print each with its type. Now reassign replicas from int to a str β€” what changes?
  2. Write a script that takes a server name as input and prints: "Connecting to: <server_name>". What type does input() always return?
  3. Explain with code why print = 100 breaks things and how you would fix it without restarting Python.

DevOps-Focused

  1. Config Validator Script: Write a script that stores 5 deployment config values (instance type, port, region, replica count, environment name). Print each value, its type, and its memory id. Then change port from int to str (e.g., from 8080 to "8080") and explain the real-world implication in a comment.
  2. Build Status Logger: Write a script that uses input() to ask for a build status (SUCCESS/FAILED), stores it in a variable, and prints: "Pipeline result: <status> | Type: <type>". Add a comment explaining why you'd never name this variable input or print.

Python for DevOps & Cloud*

Top comments (1)

Collapse
 
topstar_ai profile image
TopStar AI

This is a fantastic beginner-friendly breakdown of Python essentials for DevOps and cloud workflows. I really appreciate how you tie core conceptsβ€”like print(), variables, dynamic typing, and identifiersβ€”to real-world DevOps use cases, such as managing AWS instances, Docker/Kubernetes configuration, and CI/CD pipelines.

Your emphasis on avoiding shadowing built-ins, respecting keywords, and using snake_case for clarity is especially important for beginners who are learning best practices early.

I’d love to collaborate or exchange exercisesβ€”perhaps we could create a series of guided Python challenges specifically tailored to DevOps and cloud automation, building from basics to more advanced tasks like configuration validation and deployment logging. This could be a great way to help beginners bridge theory and practical application.

Would you be open to discussing that further?