I am learning python. I am creating a program to printing Stars '*' in D Shape using for loop. I am using the following code.
for row in range(7):
for col in range(5):
if (col==0 or (col==4 and row!=0 and row!=6)) or ((row==0 or row==6) and (col!=0 and col!=4)):
print("*", end="")
else:
print(end=" ")
print()
In if statements first section, if I use row>0 and row<6, I get the same result. Now I am confused which operator I should use.
col==4 and row!=0 and row!=6
CodePudding user response:
It doesn't matter.
Since row iterates on range(7), it can only assume the values of 0, 1, 2, 3, 4, 5 and 6.
The condition
row != 0applies to 1, 2, 3, 4, 5 and 6.The condition
row > 0applies to 1, 2, 3, 4, 5 and 6.The condition
row != 6applies to 0, 1, 2, 3, 4 and 5.The condition
row < 6applies to 0, 1, 2, 3, 4 and 5.
So in this specific case, you can use them interchangeably (however, I consider > and < to be more readable).
CodePudding user response:
Your rows go from 0 to 6 so:
- row != 0 and row != 6 --> everything except the outer two
- row > 0 and row < 6 ---> everything between the outer two
CodePudding user response:
The reason why row > 0 and row < 6 and row != 0 and row != 6 in this use case results to the same condition is because your row will only get the values of 0 1 2 3 4 5 6.
row > 0 and row < 6 means 1 2 3 4 5
row != 0 and row != 6 means 1 2 3 4 5
CodePudding user response:
Both are ok, but in either case, I'd chain:
0 != row != 6
0 < row < 6
