Python assert not working: limit user enter only stated numbers but assert not working

Viewed 42

Beginner here. I try to create a lottery game by with 6 numbers entry. The code below try to check the user enter the numbers: first, whether it's integer; second whether it's in the range which stated. However, the check of int by ValueError was working but not the range of number check by assert.

def buy_lottery_ticket():
    global credit
    credit -= 5
    while True:
        try:
            entered_numbers = input('Enter your 6 favorites numbers!(1 ~ 20): ')
            entered_numbers_list = entered_numbers.split(',')
            ticket_numbers = {int(n) for n in entered_numbers_list}
            print(ticket_numbers)
            return ticket_numbers
            assert 0 < entered_numbers_list < 21
        except ValueError:
            print("Not an integer! Please enter an integer.")
        except AssertionError:
            print("Please enter an integer between 1 and 20")
        else:
            break

Appreciate your input and help. Thanks in advance.

2 Answers

Anything after return will not execute (unless the return statement raises an error). Plus, to get the length of an object such as list, use the len function.

assert 0 < entered_numbers_list < 21
return ticket_numbers

Hope this helped.

You are trying to check for 6 numbers and the range values after the return statement. Here's a way to do the same thing.

Also, in your code, you have credit -= 5. Not sure where you are setting the value first. You may want to look into it. I have commented out that line of code.

def buy_lottery_ticket():
    global credit
    #credit -= 5
    while True:
        entered_numbers = input('Enter your 6 favorites numbers!(1 ~ 20): ')
        try:    
            entered_numbers_list = entered_numbers.split(',')
            ticket_numbers = {int(n) for n in entered_numbers_list}
            if len(ticket_numbers) > 6:
                print ('You must enter only 6 unique numbers')
                continue
            elif len(ticket_numbers) < 6:
                print ('You must enter at least 6 unique numbers')
                continue
            if min(ticket_numbers) < 1 or max(ticket_numbers) > 20:
                print ("Please enter an integer between 1 and 20")
                continue
            print(ticket_numbers)
            return ticket_numbers
        except ValueError:
            print("Not an integer! Please enter an integer.")

print (buy_lottery_ticket())

The output of this will be:

Enter your 6 favorites numbers!(1 ~ 20): 5,7,15,17,3,8,9
You must enter only 6 unique numbers
Enter your 6 favorites numbers!(1 ~ 20): 5,7,15,17,3
You must enter at least 6 unique numbers
Enter your 6 favorites numbers!(1 ~ 20): 5,7,15,17,3,15
You must enter at least 6 unique numbers
Enter your 6 favorites numbers!(1 ~ 20): 5,7,15,17,3,8
{3, 5, 7, 8, 15, 17}
{3, 5, 7, 8, 15, 17}
Related