为何Python未执行for循环内的if语句?
问题:爱情计算器for循环内的if语句始终不执行
我在编程课项目中制作了一款包含列表与for循环的爱情计算器,但无论如何,for循环内的if语句始终不执行。我已添加调试手段,确认并非t+=1代码的问题,完全无法理解其无法正常运行的原因,恳请帮助。
原代码
x = input('Enter your name:\n'); y = input('Enter other\'s name:\n'); t = 0 love = ['l', 'o', 'v' , 'e']; for i in x: print(i); if i in ['l', 'o', 'v' , 'e']: print(i); t += 1 for i in y: print(i); if i in ['l', 'o', 'v' , 'e']: print(i); t += 1 lp = ((len(x) + len(y))*t) print(f'Love percenatge between [{x.title()}] and [{y.title()}]: {lp:.2f}%')
问题原因
核心问题是大小写不匹配:代码里判断的是小写的['l','o','v','e'],但用户输入名字时大概率会用首字母大写(比如"Alice"里的"A","Bob"里的"B"),或者全大写,导致循环遍历到的字符和判断列表里的小写字母匹配不上,if语句自然不会执行。
解决方案
有两种简单的修复方式:
方式1:将输入的名字统一转为小写后遍历
把遍历的对象改成x.lower()和y.lower(),这样不管用户输入大小写,都会转成小写再和判断列表匹配:
x = input('Enter your name:\n'); y = input('Enter other\'s name:\n'); t = 0 love = ['l', 'o', 'v' , 'e']; # 转小写后遍历 for i in x.lower(): print(i); if i in love: print(i); t += 1 for i in y.lower(): print(i); if i in love: print(i); t += 1 lp = ((len(x) + len(y))*t) print(f'Love percentage between [{x.title()}] and [{y.title()}]: {lp:.2f}%')
方式2:扩展判断列表,包含大小写字母
把判断的列表改成同时包含大小写的字符,这样不管输入是大写还是小写都能匹配:
x = input('Enter your name:\n'); y = input('Enter other\'s name:\n'); t = 0 # 包含大小写的判断列表 love = ['l', 'L', 'o', 'O', 'v', 'V' , 'e', 'E']; for i in x: print(i); if i in love: print(i); t += 1 for i in y: print(i); if i in love: print(i); t += 1 lp = ((len(x) + len(y))*t) print(f'Love percentage between [{x.title()}] and [{y.title()}]: {lp:.2f}%')
内容的提问来源于stack exchange,提问作者sasanonozozo
相关产品推荐
相关产品推荐

