前言
大家好,我是倔强青铜三。欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!
欢迎来到 Python 百日冲刺第 38 天!
今天,我们把平平无奇的 input()
玩出花:类型转换、异常兜底、循环校验、批量读取、布尔识别、JSON 直传、默认值回退,一站式教你写出“用户永远输不错”的交互脚本。
🧠 input()
的本质
name = input("Enter your name: ")print(f"Hello, {name}!")
记住:返回值永远是字符串。任何数字、列表、布尔都得自己洗。
🔢 数字输入:强制转换 + 异常处理
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!")
🔄 循环到对为止
while True: user_input = input("Enter a number: ") try: number = float(user_input) break except ValueError: print("Please enter a valid number!")
📦 批量输入:一行搞定
# 读取 name 与 agedata = 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 识别器
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.")
🛠️ 封装成万能工具函数
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 直传:让高级用户直接贴配置
import jsonraw = input("Paste JSON here: ")try: obj = json.loads(raw) print("Parsed:", obj)except json.JSONDecodeError: print("Invalid JSON")
🔧 带默认值的优雅输入
Python 没有原生默认值,但可以模拟:
def input_with_default(prompt, default="yes"): user_input = input(f"{prompt} [{default}]: ").strip() return user_input if user_input else defaultresponse = 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
+ 循环 + 封装函数,就能让用户怎么输都对!
最后感谢阅读!欢迎关注我,微信公众号:
倔强青铜三
。欢迎点赞
、收藏
、关注
,一键三连!!!