According to how I understood the operator statement-when given "statement x" and "statement y"
, assuming that both statements, x and y, are True
. Given that, the and
operator represented will check if statement x
is True, then will move on to statement y
and will do the same. But once it finished checking the final statement (y) when trying to check (in other words 'refer' to the statements) the statements in the "statement x" and "statement y"
, we could ONLY check the final statement, IE statement y
According to this logic, the first snippet's output, is indeed correct, which confirms my understanding.
variable1 = "this is variable 1"
variable2="this is variable 2"
def returning(var1,var2):
return var1 and var2
print(returning(variable1,variable2))
According to my logic, for the second snippet, the loop should never stop because the and
operator only checks the y
statement. But, the loop stops, which contradicts my logic. Why is there is this contradiction? in other words What is invalid in my understanding of operators?
x = 3
y = 2
while(x and y):
print("iteration has been made")
x=x-1
user_input = input("Enter something (type 'quit' to exit): ")
if user_input == "quit":
break
x
become False
when is equal to 0 (x = x - 1), that's why the loop stops:
x = 3
y = 2
while(x and y):
print(f'Loop x={x}')
x = x - 1
print(f'Last x={x})
Output:
Loop x=3 # x and y is True
Loop x=2 # x and y is True
Loop x=1 # x and y is True
Loop x=0 # x and y is False, because x=0
Read Truth Value Testing