1

I have an if statement that is picking which diameter is closest to the avg. In the statement I have the same variable equal to the vertical_tube_d for both if and else because later in the code i am writing to a file and needed one common variable. So the code is supposed to pick the closest and later in the code write that diameter.

def pick_diameter(d1, d2, avgd):
    if abs(avgd-d1) < abs(avgd-d2):
        vertical_tube_d = d1
    else:
        vertical_tube_d = d2

Is this a problem/will it confuse the computer?

  • 2
    Why do you think it would confuse the computer? Looks perfectly reasonable to me. – Mark Ransom Jun 27 '22 at 17:40
  • You'll need a "return vertical_tube_d" line at the end of the function, but other than that it should work as I think you intend. For this sort of thing, it's generally fastest & best to open up the Python REPL (by typing "python" at the command line) and messing around with options and different inputs. StackOverflow generally focuses on "there's a bug here, but I don't know what caused it"... – Sarah Messer Jun 27 '22 at 17:40

1 Answers1

2

There is no problem with your code. I suggest next time to test it yourself, rather than ask a Stack Overflow question, though. As a matter of style, I would prefer to write it briefly like so:

def pick_diameter(d1, d2, avgd):
    vertical_tube_d = d1 if abs(avgd-d1) < abs(avgd-d2) else d2 

SEE ALSO:

Python ? (conditional/ternary) operator for assignments

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47