我對 python 編程很“新”。我正在盡力使我的代碼看起來不錯并且運行良好。我使用 Pycharm 作為我的 IDE。我正在為自己做點什么。我玩桌面角色扮演游戲,我正在嘗試為我玩的游戲創建角色創建者。我的一切運行良好,但 Pycharm 告訴我“運算式可以簡化”和“PEP 8:E712 與 True 的比較應該是“如果 cond 不是 True:”或“如果不是 cond:”
這是有問題的代碼:
fname = False
while fname != True:
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 new_character.firstName.isalpha() != True:
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() == True):
fname = True
Pycharm 告訴我,我的“while fname != True:”和“if new_character.firstName.isalpha() != True:”一樣是可以簡化的部分。
我已經嘗試在谷歌上搜索我正在做的事情的解決方案,但其中大多數都是為了有點像我要問的東西,但從來沒有使用 != True 部分。我什至聯系了我的一個 Python 程式員朋友,但我還沒有收到回復。
再次,我想宣告,就像現在一樣,代碼按照撰寫的方式正常作業,我只是想了解是否有辦法讓代碼看起來更干凈/更整潔或執行相同的功能并被簡化不知何故。
任何有關如何潛在地簡化這些代碼行并維護功能的指標將不勝感激。
uj5u.com熱心網友回復:
這是您可以重寫此代碼以使其更易于閱讀和更高效的一種方法:
# Loop until the user provides a good input
while True:
# Set a temp variable, don't constantly reassign to the new_character.firstName attribute
name = input('What would you like your first name to be?\n').capitalize()
# If the name isn't between 2 and 20 characters, start the loop over at the beginning
if not (1 < len(name) <= 20):
print('Name does not meet length requirements. Please try again.')
continue
# If the name contains anything other than letters, start the loop over at the beginning
if not name.isalpha():
print('Please do not use numbers or special characters in your name. Please try again.')
continue
# You can only reach this break if the name "passed" the two checks above
break
# Finally, assign the character name
new_character.firstName = name
您可以做的進一步簡化的一件事是同時檢查這兩個條件,并列印更有用的錯誤訊息,明確地重新陳述要求:
NAME_ERROR_MESSAGE = """
Invalid name '{name}'. Your character's name
must be between 2 and 20 characters long, and
contain only letters. Please try again.
"""
while True:
name = input('What would you like your first name to be?\n').capitalize()
if (1 < len(name) <= 20) and name.isalpha():
new_character.firstName = name
break
print(NAME_ERROR_MESSAGE.format(name=name)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/532947.html
標籤:Python
上一篇:使用正則運算式從字串中提取鍵值對
下一篇:鏈接抓取錯誤
