Finishing If Statements
Hello, guys! How are you? The "finally" command allows a block to be executed after error checking no matter what happened before, right? Is there any similar command for the "if" block? I have the following code, simulating an item being equipped with an RPG character. https://code.sololearn.com/cP408MykV8e0/#py What can I do to improve the code? I mean, inserting a self.update_parameters () after each if check is really the best option?
1/12/2020 11:49:26 AMrfPeixoto
4 AnswersNew Answer
Firstly I am guessing you didn't post the whole code - just a snippet(?). If you want to execute something regardless of the if-else block you can add it just after the block, that is, with the same indentation. https://code.sololearn.com/c99DXXOquB1x/?ref=app
Try to keep in mind the DRY principle (Don't repeat yourself). Considering you always update the same index as the id, the equip function could be refactored like this: if 0 <= item.id <= 3: self.equipments[item.id] = item.parameter Your program could also raise a ValueError for example if the ID is not correct. After the if statement you can still add more code, that will execute regardless of the condition, just indent them at the same level as the 'if'
@Black Jesus Yes, I posted the excerpt just to exemplify the problem. But you and @Danigamy can see the entire code here: https://code.sololearn.com/cs5275zK925t/#py Thanks to everyone and especially @Tibor Santa. I had not realized that I was looking for the same IDs and could have done something like that. Problem solved, guys. o/
No output? https://code.sololearn.com/csv4qvv3S7lg/?ref=app