I have no Idea if the title uses the correct terms but I am looking to get some code and to try and reduce the length of the code so It will be quicker for me to type in the assessment. Here is and Example of How it would look if I did it the long winded way.
Valid = True
while Valid:
Column = int(input("Insert Column: "))
Row = int(input("Insert Row: "))
if Row < 0 or Row > 9 or Column < 0 or Column > 9:
Valid = False
However, I was trying to to make that smaller by doing something along the lines of:
"If (Row or Column) < 0 or (Row or Column) > 0:
valid = False"
Can someone explain why it doesn't seem work and can someone please demonstrate how they would solve it. I am only trying to slim down my if statements since throughout the assessment I will be using a large amount of them.
Update:- Can this also be put into a Try - Catch so it wouldn't crash the program upon entering a Null Value or No value
Thanks
You can remove the if statement completely.
Valid = True
while Valid:
try:
Column = int(input("Insert Column: "))
Row = int(input("Insert Row: "))
Valid = Row in range(10) and Column in range(10)
except Exception as e:
print(e)
Valid = False
The or operator is a short-circuiting comparison that returns the earliest truthy value, or the last value if none are truthy. In (Row or Column) < 0, first Row or Column is evaluated. If Row is nonzero, that section returns Row. Otherwise, it would return Column. It then compares this single value to 0. The same goes for the other comparison, which I assume has a typo and was intended to be (Row or Column) > 9 (rather than > 0).
You can also try the following (not an exhaustive list):
if not 0<=row<=9 or not 0<=column<=9
if row not in range(10) or column not in range(10)
if not all(0<=x<=9 for x in (row,column))
Choose the one that makes the most sense in the context of your program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With