How to create conditional instance attribute in python which can only take value >= 5000,else prompt user that minimum is 5000?

Question:

I have class ‘Player’ in python and wanna create instance attribute ‘deposit’,which intended take integer equal or greather 5000,else raise error or to ask user set valid value.So I tried implement that with ‘if else’ but it is not the satisfying result.

class Player:

def __init__(self, deposit):
    if deposit >= 5000:
        self.deposit = deposit
    else:
        print('Minimum deposit is 5000')
        

pl = Player(4000)
pl.deposit // AttributeError: ‘Player’ object has no attribute ‘deposit’

Asked By: cardinal2000

||

Answers:

You are getting an AttributeError because the deposit attribute is not created when the deposit value is less than 5000.
If you want to prompt the user to set a valid deposit value when the deposit is less than 5000, you can use a loop and the input() function to prompt the user until a valid deposit value is entered like this:

class Player:
    def __init__(self, deposit):
        while deposit < 5000:
            print('Minimum deposit is 5000')
            deposit = int(input('Enter a valid deposit value: '))
        self.deposit = deposit

pl = Player(4000)
pl.deposit

And if you want to just raise the error you can do it like this:

class Player:
    def __init__(self, deposit):
        if deposit >= 5000:
            self.deposit = deposit
        else:
            raise ValueError('Minimum deposit is 5000')

pl = Player(4000)
pl.deposit
Answered By: Ake
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.