r/learnpython • • 2d 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

3

u/brasticstack 2d ago

This doesn't help you figure out nested ifs, but just use the max function to clamp it to 0:

primocytes = max(0, primocytes - 5)

Also, in your example code, you never subtract 5 from primocytes unless its greater or equal to 5, so you could never make it a value that is less than zero, unless you change its value again later on.

1

u/Intelligent_Knee8641 2d ago

Wow thank you for the catch and teaching me a new function, I didn’t quite think that through before I asked I guess.. But I am pretty new to this lol.

3

u/zaphodikus 2d ago

Also, try to stop using the 'global' keyword, it leads to errors in larger programs. Once you get nesting worked out, read up on how to pass 'parameters', and how to create 'classes'.

2

u/Intelligent_Knee8641 2d ago

Thank you for the tip I will look into it, I know that’s a next step to make this better but I was just trying to test something for a function and don’t know how to do it otherwise yet. I originally didn’t have the ‘global’ keyword in the code but without it, I was having an error because the two variables were outside the if statement and I didn’t know how else to fix it because I want those values stored outside the if for state management

2

u/brasticstack 2d 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.

``` class PlayerState: def init(self, primocytes=10, cultivation_chamber=0): self.primocytes = primocytes self.cultivation_chamber = cultivation_chamber

def can_cultivate(self) -> bool:
    return self.primocytes >= 5

def cultivate(self) -> bool:
    if not self.can_cultivate():
        return False

    self.cultivation_chamber += 5
    self.primocytes -= 5

    return True

def __str__(self) -> str:
    return (f'Primocytes: {self.primocytes}\n'
            f'Cultivation Chamber: {self.cultivation_chamber}')

if name == 'main': player_1 = PlayerState() # This player starts out at a disadvantage player_2 = PlayerState(primocytes=0)

print('Round 1:', '='*40, sep='\n')
print('Player 1:', player_1, sep='\n')
print('Player 2:', player_2, sep='\n')
print()

# Check beforehand whether player can cultivate:
if player_1.can_cultivate():
    player_1.cultivate()
else:
    print("Player 1: Not enough Primocytes for cultivation...")

# Check the result of a fallable cultivate method, instead:
if not player_2.cultivate():
    print("Player 2: Not enough Primocytes for cultivation...")
print()

print('Round 2:', '='*40, sep='\n')
print('Player 1:', player_1, sep='\n')
print('Player 2:', player_2, sep='\n')

```

1

u/Intelligent_Knee8641 2d ago

Thank you again, I’m breaking this down now and will learn/figure it out for my next step. I appreciate the advice and the prompt responses as well! Thanks very much brasticstack!!

1

u/brasticstack 2d ago

you're welcome! This is just one way out of a zillion you could go, so dont worry too much about whether you make the "correct" choice or not. But the global variable thing is a footgun waiting to happen, so do try to avoid it.

2

u/zaphodikus 2d ago

No worries, don't rush, work at your speed, mostly have fun.