寻求Python实现输出数量与单位关联的教程及代码指导
实现指定单位和数量的随机数值生成程序
先给你修正并优化后的完整代码:
import random # 获取并验证单位输入 while True: bmi_unit = input("Enter the units: kg or pounds ").strip().lower() if bmi_unit in ['kg', 'pounds']: break print("Incorrect input. Please enter kg or pounds") # 获取并验证输出数量输入 while True: try: bmi_sample = int(input("Enter a number of outputs : ").strip()) if bmi_sample > 0: break print("Please enter a positive integer") except ValueError: print("Invalid input. Please enter a number") # 生成并打印对应数量的随机数值 for i in range(bmi_sample): if bmi_unit == 'pounds': weight = random.randint(10, 20) print(f"{bmi_unit} {i+1} = {weight} pounds") else: # 用更精确的磅转千克系数 pound_weight = random.randint(10, 20) kg_weight = round(pound_weight / 2.20462, 2) print(f"{bmi_unit} {i+1} = {kg_weight} kg")
关键修改和逻辑说明:
- 单位输入校验优化:替换原错误的while条件,改用循环直接判断输入是否符合要求,同时通过
strip().lower()兼容用户输入的空格、大小写差异(比如输入" Pounds "也能正常识别) - 输出数量校验:增加异常处理,强制用户输入正整数,避免非数字输入导致程序崩溃
- 变量修正:把原代码中写死的循环范围替换为用户输入的有效数值,打印时使用变量而非固定字符串,保证内容准确性
- 数值转换优化:使用更精确的磅转千克系数2.20462,提升结果准确性
- 格式化输出:用f-string简化打印语句,让代码更易读维护
核心功能拆解:
- 输入验证:确保单位为指定的两种类型,输出数量为有效正整数
- 随机数生成:根据单位选择,生成对应范围的随机数值(磅直接用整数范围,千克通过磅转换或可直接用
random.uniform(4.5, 9.1)生成浮点随机数) - 循环输出:按照用户指定的数量,依次打印带序号的随机数值
内容的提问来源于stack exchange,提问作者user16674853
相关产品推荐
相关产品推荐

