苦练Python第38天:input() 高级处理,安全与异常管理

前言

大家好,我是倔强青铜三 。欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!

欢迎来到 Python 百日冲刺第 38 天

今天,我们把平平无奇的 input() 玩出花:类型转换、异常兜底、循环校验、批量读取、布尔识别、JSON 直传、默认值回退,一站式教你写出"用户永远输不错"的交互脚本。


🧠 input() 的本质

python 复制代码
name = input("Enter your name: ")
print(f"Hello, {name}!")

记住:返回值永远是字符串。任何数字、列表、布尔都得自己洗。


🔢 数字输入:强制转换 + 异常处理

python 复制代码
try:
    age = int(input("Enter your age: "))
    print(f"You will be {age + 1} next year.")
except ValueError:
    print("That's not a valid number!")

🔄 循环到对为止

python 复制代码
while True:
    user_input = input("Enter a number: ")
    try:
        number = float(user_input)
        break
    except ValueError:
        print("Please enter a valid number!")

📦 批量输入:一行搞定

python 复制代码
# 读取 name 与 age
data = input("Enter name and age (e.g., John 25): ")
name, age_str = data.split()
age = int(age_str)
print(f"Name: {name}, Age: {age}")

# 读取任意数量整数
nums = input("Enter numbers separated by space: ")
numbers = [int(x) for x in nums.split()]
print(numbers)

✅ 布尔输入:Yes/No 识别器

python 复制代码
ans = input("Do you agree? (yes/no): ").strip().lower()
if ans in {"yes", "y"}:
    print("Agreed!")
elif ans in {"no", "n"}:
    print("Not agreed.")
else:
    print("Invalid response.")

🛠️ 封装成万能工具函数

python 复制代码
def get_int(prompt):
    """循环直到拿到合法整数"""
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Please enter a valid integer.")

age = get_int("Enter your age: ")
print(age)

📄 JSON 直传:让高级用户直接贴配置

python 复制代码
import json

raw = input("Paste JSON here: ")
try:
    obj = json.loads(raw)
    print("Parsed:", obj)
except json.JSONDecodeError:
    print("Invalid JSON")

🔧 带默认值的优雅输入

Python 没有原生默认值,但可以模拟:

python 复制代码
def input_with_default(prompt, default="yes"):
    user_input = input(f"{prompt} [{default}]: ").strip()
    return user_input if user_input else default

response = input_with_default("Continue?")
print(response)

🧾 速查表

需求 示例代码片段
基础文本 input("Name: ")
整数 int(input(...))
浮点 float(input(...))
防错循环 while True: try ...
多值空格分割 input().split()
列表解析 [int(x) for x in input().split()]
布尔 input().strip().lower() in {"yes","y"}
JSON json.loads(input())
默认值 input() or default

✅ 一句话总结

input() 天生返回字符串,用好 try-except + 循环 + 封装函数,就能让用户怎么输都对!

最后感谢阅读!欢迎关注我,微信公众号倔强青铜三。欢迎点赞收藏关注,一键三连!!!

相关推荐
不要再敲了25 分钟前
JDBC从入门到面试:全面掌握Java数据库连接技术
java·数据库·面试
西猫雷婶1 小时前
pytorch基本运算-Python控制流梯度运算
人工智能·pytorch·python·深度学习·神经网络·机器学习
说私域1 小时前
新零售第一阶段传统零售商的困境突破与二次增长路径:基于定制开发开源AI智能名片S2B2C商城小程序的实践探索
人工智能·开源·零售
子午1 小时前
Python的uv包管理工具使用
开发语言·python·uv
java1234_小锋1 小时前
Scikit-learn Python机器学习 - 分类算法 - 朴素贝叶斯
python·机器学习·scikit-learn
凡梦千华1 小时前
Django时区感知
后端·python·django
Nan_Shu_6141 小时前
Web前端面试题(1)
前端·面试·职场和发展
寒月霜华2 小时前
机器学习-模型验证
人工智能·深度学习·机器学习
救救孩子把2 小时前
3-机器学习与大模型开发数学教程-第0章 预备知识-0-3 函数初步(多项式、指数、对数、三角函数、反函数)
人工智能·数学·机器学习