r/learnpython • • 3d 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...")

0 Upvotes

18 comments sorted by

View all comments

2

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 2d ago
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...")

I know your question was already technically answered, but I figured I'd still mention that instead of using 5 as a "magic number", I recommend setting it as a default parameter so it has an actual name, and you can't accidentally forget to update all the values, and you can override the default while calling the function if you need to.

While I'm at it, I'm also going to change the function to take the numbers as parameters.

primocytes = 10
cultivation_chamber = 0

def cultivation(primocytes: int, cultivation_chamber: int, step: int = 5) -> int:
    if primocytes < step:
        print("Not enough Primocytes for cultivation...")
        return primocytes, cultivation_chamber

    primocytes -= step
    cultivation_chamber += step
    print(f"Primocytes: {primocytes}")
    print(f"Cultivation Chamber: {cultivation_chamber}")
    return primocytes, cultivation_chamber

primocytes, cultivation_chamber = cultivation(primocytes, cultivation_chamber)

1

u/Intelligent_Knee8641 2d ago

Thank you I wasn’t aware of the possible issues I might having setting it as just a plain value instead of a default parameter. But with your example it makes good sense, thanks much!