Python布尔语句简化求助:PyCharm提示PEP 8规范优化
解决PyCharm的PEP 8提示与代码简化问题
针对你代码里的PEP 8提示和简化需求,这里是修改后的代码,完全保留原有功能且符合规范:
fname = False while not fname: new_character.firstName = input('What would you like your first name to be?\n').capitalize() if 1 >= len(new_character.firstName) or len(new_character.firstName) > 20: print('Name does not meet length requirements. Please try again.') if not new_character.firstName.isalpha(): print('Please do not use numbers or special characters in your name. Please try again.') if (1 < len(new_character.firstName) < 20) and new_character.firstName.isalpha(): fname = True
关键修改说明:
while fname != True:→while not fname::布尔变量本身可直接用于条件判断,取反操作not比与True做不等比较更简洁,完全符合PEP 8 E712规范。if new_character.firstName.isalpha() != True:→if not new_character.firstName.isalpha():isalpha()方法本身返回布尔值,直接对结果取反即可,无需额外与True比较,消除了“Expression can be simplified”提示。- 顺带优化了最后一个条件里的
== True:去掉冗余的比较,直接使用new_character.firstName.isalpha()作为布尔条件,代码更简洁。
内容的提问来源于stack exchange,提问作者Billy Blanks
相关产品推荐
相关产品推荐

