4.11 Input Statement
Python input() in detail: syntax, type conversion, validation, multiple values, piped stdin, and practical AWS, Kubernetes, Docker, and CI/CD examples.
What Is input()?
input() reads one line from standard input, optionally displays a prompt, waits until the user presses Enter, removes the line ending, and returns the remaining text as a string.
It is useful for small interactive command-line scripts. It is not a replacement for a full command-line argument parser, environment variables, or a secret manager in production automation.
Basic Syntax
value = input(prompt)
The prompt argument is optional and must be a string. Python writes it to the console without adding a newline, then waits for input.
name = input("Enter your name: ")
print(f"Hello, {name}!")
Example interaction:
Enter your name: Alice
Hello, Alice!
The prompt can be omitted:
print("Enter the environment name:")
environment = input()
The value is assigned only when the user enters a line. input() does not automatically validate, convert, or hide anything typed by the user.
Important Properties
It Always Returns str
Even when the user enters digits, the result is text.
replica_text = input("Number of replicas: ")
print(type(replica_text)) # <class 'str'>
replicas = int(replica_text)
print(replicas + 1)
Without conversion, "3" + "1" produces "31", not 4, and "3" + 1 raises TypeError.
It Reads One Line
The user can type spaces inside the line, but pressing Enter finishes that call. To read several lines, call input() repeatedly or use a loop.
first_line = input("First line: ")
second_line = input("Second line: ")
It Removes the Trailing Newline
Unlike sys.stdin.readline(), the returned value does not include the final \\n. It can still contain leading or trailing spaces, so .strip() is often useful.
service = input("Service name: ").strip()
Common Ways to Use input()
Read Plain Text
region = input("AWS Region: ").strip()
Convert to an Integer
port = int(input("Port: "))
Use this only when invalid text should stop the program. For user-facing tools, catch ValueError and show a helpful message.
Convert to a Decimal Number
threshold = float(input("CPU threshold (%): "))
For currency or exact decimal values, prefer decimal.Decimal instead of float.
Parse a Boolean Safely
Do not use bool(input("Enable feature? ")): every non-empty string, including "no", is truthy.
answer = input("Enable monitoring? (yes/no): ").strip().lower()
if answer in {"yes", "y"}:
monitoring_enabled = True
elif answer in {"no", "n"}:
monitoring_enabled = False
else:
raise ValueError("Enter yes or no")
Read Several Values from One Line
split() separates whitespace-delimited values. Convert each item when numeric input is expected.
raw_ports = input("Ports, separated by spaces: ")
ports = [int(port) for port in raw_ports.split()]
print(ports)
For comma-separated values, provide the separator explicitly:
raw_tags = input("Tags, separated by commas: ")
tags = [tag.strip() for tag in raw_tags.split(",") if tag.strip()]
Use a Default Value
An empty response can mean “use the default”. The or expression handles that case.
region = input("AWS Region [us-east-1]: ").strip() or "us-east-1"
Ask Until the Value Is Valid
This is the standard pattern for a small interactive tool.
while True:
try:
replicas = int(input("Replicas (1-20): "))
if 1 <= replicas <= 20:
break
print("Enter a number from 1 to 20.")
except ValueError:
print("Enter a whole number.")
print(f"Deploying {replicas} replicas.")
Choose from a Menu
actions = {"1": "status", "2": "logs", "3": "restart"}
choice = input("1) status 2) logs 3) restart: ").strip()
if choice not in actions:
raise ValueError("Unknown action")
print(f"Selected action: {actions[choice]}")
Read Multiple Lines
commands = []
for number in range(3):
commands.append(input(f"Command {number + 1}: ").strip())
For an unknown number of lines, use a sentinel such as "done":
lines = []
while True:
line = input("Enter a line, or done: ").strip()
if line.lower() == "done":
break
lines.append(line)
Handling Errors and Interruptions
Invalid conversion raises ValueError. End-of-file, common when stdin is redirected or a CI job provides no input, raises EOFError. Ctrl+C raises KeyboardInterrupt.
try:
environment = input("Environment: ").strip()
replicas = int(input("Replicas: "))
except ValueError:
print("Replicas must be a whole number.")
except EOFError:
print("No interactive input was provided.")
except KeyboardInterrupt:
print("\nOperation cancelled.")
input() and Standard Input
input() reads from standard input, so a shell can pipe a value into a script. This is useful for simple, non-secret values.
echo "staging" | python deploy.py
environment = input().strip()
print(f"Received environment: {environment}")
For larger streams, use sys.stdin instead of calling input() one line at a time:
import sys
for line in sys.stdin:
print(f"Processing: {line.strip()}")
Do not pipe passwords, tokens, or cloud credentials through shell commands because they can appear in shell history, process output, or CI logs.
Cloud and DevOps Examples
Select an AWS Region and Profile
This example uses input for choices while leaving authentication to the AWS SDK credential chain. The user should already have a configured AWS profile; credentials should never be requested with input().
import boto3
region = input("AWS region [us-east-1]: ").strip() or "us-east-1"
profile = input("AWS profile [default]: ").strip() or "default"
session = boto3.Session(profile_name=profile, region_name=region)
ec2 = session.client("ec2")
response = ec2.describe_instances(
Filters=[{"Name": "instance-state-name", "Values": ["running"]}]
)
running = sum(
len(reservation["Instances"])
for reservation in response["Reservations"]
)
print(f"Running instances in {region}: {running}")
In a non-interactive pipeline, pass the region and profile as command-line arguments or environment variables instead. Interactive input can block a deployment job indefinitely.
Confirm a Potentially Destructive AWS Action
Always require an explicit confirmation before deleting or changing infrastructure.
resource_id = input("EC2 instance ID to stop: ").strip()
confirmation = input(
f"Type STOP to stop {resource_id}, or anything else to cancel: "
).strip()
if confirmation == "STOP":
print(f"Would stop {resource_id}")
# ec2.stop_instances(InstanceIds=[resource_id])
else:
print("Cancelled.")
The example leaves the API call commented out so it cannot change a real account when copied for learning.
Select a Kubernetes Context and Namespace
The input is validated before it is passed to kubectl. In production automation, prefer a reviewed allowlist and avoid constructing shell commands with shell=True.
import subprocess
context = input("kubectl context: ").strip()
namespace = input("Namespace [default]: ").strip() or "default"
if not context or not namespace:
raise ValueError("Context and namespace are required")
subprocess.run(
["kubectl", "--context", context, "--namespace", namespace, "get", "pods"],
check=True,
)
Build a Docker Image Tag
Validate a release value before using it in a Docker command or CI job.
import re
image = input("Image name [orders-api]: ").strip() or "orders-api"
tag = input("Image tag [latest]: ").strip() or "latest"
if not re.fullmatch(r"[a-z0-9][a-z0-9_.-]*", image):
raise ValueError("Invalid image name")
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", tag):
raise ValueError("Invalid image tag")
print(f"docker build --tag {image}:{tag} .")
Choose a Log Level for a Diagnostic Script
import logging
level_names = {"debug": logging.DEBUG, "info": logging.INFO, "warning": logging.WARNING}
level = input("Log level [info]: ").strip().lower() or "info"
if level not in level_names:
raise ValueError(f"Choose one of: {', '.join(level_names)}")
logging.basicConfig(level=level_names[level])
logging.info("Diagnostic collection started")
Collect a CI/CD Deployment Choice
This is suitable for a manually started local release helper, not an unattended pipeline.
environments = {"1": "dev", "2": "staging", "3": "production"}
choice = input("Deploy to 1) dev 2) staging 3) production: ").strip()
environment = environments.get(choice)
if environment is None:
raise ValueError("Invalid deployment environment")
if environment == "production":
confirm = input("Type DEPLOY to continue: ").strip()
if confirm != "DEPLOY":
raise SystemExit("Production deployment cancelled")
print(f"Starting deployment to {environment}")
input() Versus Other Configuration Methods
| Situation | Preferred method |
|---|---|
| A person chooses an option in a local script | input() |
| A scheduled job needs a value | Environment variable or config file |
| A CI job needs typed options | argparse command-line arguments |
| A password or token is required | getpass.getpass() or a secret manager |
| Many structured settings are required | YAML, JSON, or a typed configuration model |
| A script processes piped log data | sys.stdin |
For a hidden password prompt, use getpass:
from getpass import getpass
password = getpass("Password: ")
Even getpass() is usually the wrong place for production cloud credentials. Use IAM roles, workload identity, a CI secret store, or the cloud provider’s credential chain.
Quick Interview Answer
“
input(prompt)writes an optional prompt, waits for one line from standard input, removes the trailing newline, and always returns a string. I use.strip()for whitespace, convert explicitly withint()orfloat(), validate in a loop, and catchValueError,EOFError, andKeyboardInterruptwhere appropriate. For production DevOps automation, I useargparse, environment variables, or a secret manager when the script must be non-interactive or handle sensitive values.”
Common Mistakes
- Assuming
input()returns a number. Convert and validate it explicitly. - Using
bool(input(...))to parse yes/no. Any non-empty string isTrue. - Forgetting
.strip(), causing a valid-looking choice with extra spaces to fail validation. - Asking for passwords, API keys, or cloud credentials with
input(), which displays the typed value. - Using
input()in unattended CI/CD jobs, where no person is available to answer and the job can hang. - Passing unchecked input into a shell command. Prefer an argument list with
subprocess.run()and validate allowed values. - Treating an empty response as a valid resource name, region, namespace, or deployment target.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form