Why use the OR operator instead of the AND operator for a while loop?

35 Views Asked by At

So someone has briefly explained this to me, but unfortunately I still do not understand.

My thinking is, we use an AND because this means we need both conditions to be met in order to pass.

Whereas with an OR, it only requires one condition to pass. So how come in my example we are using an OR operator for both conditions to be met?

#DOUBLE == MEANS EQUALITY
#SINGLE = MEANS ASSIGNMENT

#THIS WILL BE THE LEGIT USER CHOICE WHERE OUR CHOICE HAS TO BE 
#A NUMBER THAT IS WITHIN RANGE, SO TWO VARIABLES TO MEET BIG BOY

def my_choice ():
    
    #VARIABLES SECTION
    
    #INITIALS
    choice = 'wrong'
    accepted_range = range(1,10)
    within_range = False

    #Just like our choice we have to give the false answer here to keep
    #the while loop- why? I dont know yet, will update
    
    #TWO CONDITIONS TO CHECK
    #1-MAKE SURE ITS AN ACTUAL NUMBER
    #2-MAKE SURE ITS WITHIN THE RANGE
    
    #CODE TIME
    while choice.isdigit()==False or within_range == False:
        
        choice = input('Please enter a value bettwen 1-9, Thanks ')
        
        #Digit check
        if choice.isdigit() == False:
            print('sorry mate {} is not a digit'.format(choice))
            
    
        #Range Check
        #If we have passed the digit check, we can use it in our range check
        if choice.isdigit() == True:
            #remember that input returns a string ya?
            if int(choice) in accepted_range:
                within_range = True
                print('Well done, {} is defintely a number in range'.format(choice))

            else:
                within_range = False
                print('Sorry, you have picked a number, just not in range')
    
1

There are 1 best solutions below

3
M.P. Korstanje On

If you use boolean algebra you can show that these are equivalent:

is_digit or within_range

not (is_digit and within_range) 

not is_digit and not within_range

You can also make a truth table to confirm this.