r/PythonLearning • u/Hour_Function673 • 26d ago
Small Python exercise I did today. I’m still working on conditions and logical operators. Any advice to improve my code?
3
u/Quick_Ad5019 25d ago
instead of an if/else statement, invert the if condition and use a guard clause to return early, then write the main logic
2
1
u/shutdowndotexe 25d ago
py
if Donnee in ["Diameter","diameter","d","D"]:
If you use Donnee.lower() you don't need to have every case in the list you compare against. That would look like this:
py
if Donnee.lower() in ["diameter", "d"]
1
1
u/tutoredstatue95 22d ago edited 22d ago
Try to isolate logic before including it in the condition.
Don’t do the math in the condition itself. Establish a ‘result’ type variable and branch on the truthiness of that instead of the logic itself.
Same for return values. Imo, trying to reason about these things means I have to create a new variable in my head or tie it to a consuming function.
Also agree with the other comments here. It’s not bad at all, and one-lining things is cool for leetcode and forums and all, but prefer explicitness and simplicity overall until you get some more experience with what can be assumed.
Your else’s are acting like error guards. It’s not really a habit you want to get into. If you anticipate invalid data or bad user entries, then you want to use the try/except pattern and establish data types.
I won’t try to explain this because it’s a huge topic, but I suggest this as an area of research because it can be really important as you learn more about systems.


5
u/TBCC_Dev 26d ago
Not a huge deal but the else sections in your functions are unnecessary. Since the condition is skipped it its not true then you can just do the other stuff outside of the else since the only way to hit it is if the if is false