Y
Y
yafir2021-08-20 11:02:43
Python
yafir, 2021-08-20 11:02:43

How to make it so that when subtracting it does not go into a minus?

import random

player1 = {'player': 'Yarik', 'oranges': 30}
player2 = {'player': 'Egor', 'oranges': 30}

maxkick = 10

kick = random.randint(0, maxkick)
player2 ['oranges'] = player2['oranges'] - kick
print(kick, player2['oranges'])

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Eremin, 2021-08-20
@Sergei_Erjemin

It is obvious that the check will go to minus or not. For example like this:

kick = random.randint(0, maxkick if maxkick < player2['oranges'] else player2['oranges'])
player2['oranges'] = player2['oranges'] - kick

In general, it depends on what kind of value distribution is kick needed .

A
Alan Gibizov, 2021-08-20
@phaggi

There are many ways how to do it. You can check before subtracting whether the subtrahend is greater than the minuend. After subtraction, you can check if the value has become less than zero, and reset it to zero. In general, you can make your own type “only positive numbers”, in which you can provide control logic inside so that it does not become less than zero - either reset to zero or return an error.
To choose, you need to understand why and what will happen next.

O
o5a, 2021-08-20
@o5a

If the question is how not to go negative (regardless of what we subtract), then you can do this:

player2['oranges'] = max(player2['oranges'] - kick, 0)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question