hihibear
hihibear

Reputation: 1

Trying to check if the number the user entered through the input function is within a range of numbers

I am currently still learning Python using a course on Udemy. I've reached a project where I have to code out a BlackJack game.

if self.total not in range(0,1000): 
self.total = int(input("How many chips would you like to bring to the table? (0 - 1000): "))

something like this.

I want the input to continue running if the number they provided is not within 0 to 1000. But I am getting an error with the syntax, specifically the (in) keyword.

I tried using a while loop, but the same syntax error kept appearing. I checked and (in) can be used to check if a number is within a range(). So what am I missing here?

I also forgot to mention that this project requires us to use Object-oriented Programming, and creating our own classes.

Upvotes: 0

Views: 118

Answers (2)

Adon Bilivit
Adon Bilivit

Reputation: 26925

It is very common to see code of this style:

x = int(input('Enter a number: '))

This is very bad practice because any value entered that cannot be represented as an integer will cause a ValueError to be raised and unless handled properly the program will terminate.

Here's a more robust approach. Yes, there's a lot more code but it will keep you out of trouble.

def get_chips(lo, hi):
    while True:
        inval = input(f'How many chips would you like to bring to the table? ({lo} - {hi}): ')
        try:
            chips = int(inval)
            if lo <= chips <= hi:
                return chips
            raise ValueError('Not in range')
        except ValueError as e:
            print(f'{e} - Please try again')

print(get_chips(0, 1000))

Upvotes: 1

user16004728
user16004728

Reputation:

  1. The statement x in y requires that y is a list

    Hence you should use if self.total not in [i for i in range(0,1000)]

  2. The above would yield pretty poor performance during runtime, because in the worst case, the value of self.total would be compared to each element in the list

    Hence, since self.total is integer, you should use if 0 <= self.total <= 1000

  3. Note that 1000 is in fact not in range(0,1000), because this range runs from 0 to 999

    If that is what you actually intended for, then you should use if 0 <= self.total < 1000

Upvotes: 0

Related Questions