Python IF与Elif语句失效求助:重量转换函数输入无响应
修复重量转换函数的问题
修复后的完整代码
def weight_converter(): print("Welcome to Weight Converter") operation = int(input(" 1. Gram to Pound \n 2. Pound into Gram\nEnter your choice: ")) if operation == 1: gram_one = int(input("Grams needed to convert to pound: ")) print("You have", gram_one / 453.592, "pounds") elif operation == 2: pound_one = int(input("Pounds needed to convert to gram: ")) print("You have", pound_one * 453.592, "grams") weight_converter()
关键修复点
- 类型不匹配:原代码将
operation转为整数类型,但判断条件用了字符串" 1"、" 2",整数与字符串无法匹配,导致分支不执行。修复后直接用整数1、2做判断。 - 缩进错误:Python对缩进有严格要求,原代码中
if和elif前多了空格,会触发语法错误。修复后统一使用4个空格缩进符合Python编码规范。 - 拼写与逻辑缺失:原代码中
inpu()是拼写错误,应为input();第二个分支缺少输入提示和转换结果打印逻辑,修复后补充完整。 - 换算逻辑错误:1磅约等于453.592克,克转磅需除以该数值,原代码误用乘法导致结果错误,修复后修正了换算方向。
内容的提问来源于stack exchange,提问作者Gopesh Pandey
相关产品推荐
相关产品推荐

