Zum Hauptinhalt springen
••••••••••••••••••••
Intelligence View
⚡ tsecurity.de Intelligence

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 Dy…

Beitrag
0
Seite
0
↗ Quelle (dev.to)
Social ReaktionenReagiere als Erste:r — dein Feedback zählt!




📌 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)












🔍 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









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)









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






⚠️ 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









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!)






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']









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






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}")












❌ 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!












🏋️ 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))









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*

🔍 CTI & Forensik

Cyber Threat Intelligence & Forensik

ATT&CK-Navigator · IoC-Radar · Exploit-Belege
CTI Threat Relationship Graph
Akteure · Techniken · Beziehungen
3 Knoten · 2 Relationen
CVE / Incident Threat Actor Software MITRE ATT&CK CWE Weakness IoC
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Python Basics — `print()`, Variables, Identifiers, Data Types

Thematisch verwandte Begriffe: Python, Basics, print, Variables · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

💬 Kommentare werden geladen…
Zum Aktualisieren ziehen
tsecurity.de Icon
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag