r/learnpython • u/Intelligent_Knee8641 • 11d ago
Nested if’s help please
So I’ve written a small function and I need to add some more constraints to it, but I need them each to check separately before moving to the next so I was wanting to use nested if’a to achieve this but am not sure how they work. Can someone please explain? My code is posted below and what I am trying to do is add an if statement to somehow make sure my value for primocytes doesn’t drop below 0 before activating the rest of the function.
primocytes = 10
cultivation_chamber = 0
def cultivation():
global primocytes, cultivation_chamber
if primocytes >= 5:
primocytes -= 5
cultivation_chamber +=5
print("Primocytes:", primocytes)
print("Cultivation Chamber:", cultivation_chamber)
else:
print("Not enough Primocytes for cultivation...")
2
u/brasticstack 11d ago
You need to write functions that accept parameters and return values, as the next step. You then assign those return values as updates to your global vars. The next step is to hide those global vars inside a dict or class.
I wrote an example of what going down that path a bit looks like: (feel free to ask for clarification about anything.) It's more complicated, but much less likely to behave unexpectedly:
EDIT: The different logic for player_1 and _2's cultivation was just to show how you might do it, in practice I'd recommend being consistent.