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
  • 2
    Why do you think it would confuse the computer? Looks perfectly reasonable to me. Commented Jun 27, 2022 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"... Commented Jun 27, 2022 at 17:40

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. Or, even more simply: return d1 if abs(avgd-d1) < abs(avgd-d2) else d2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.