Hey everyone! I recently put together a square root calculator in Python as a beginner to intermediate user, and I'm looking for some feedback on my code. I'd love to know how I can clean it up or make it more efficient. I even added functionality to handle negative integers in my latest update! You can check out my code here: https://github.com/Agent10293/Square-root-calculator/tree/main
3 Answers
It’d be great to see your code somewhere public. Have you considered posting it somewhere other than GitHub?
Great job overall! Here are some suggestions to improve your code:
1. Try to separate the calculation logic into its own function, which helps organize your program better.
2. You don’t need to initialize variables like num1 and num2 to zero if you’re not using them right away.
3. Consider what happens if a user enters something that's not an integer—handling errors is crucial.
4. Instead of checking if startnum is greater than zero, just use the absolute value directly when reading input.
5. If you're using a loop that breaks after 1000 iterations, it’s better to raise an exception instead of providing a potentially incorrect answer when calculations take too long.
6. You can simplify your count check by integrating it directly into your while loop condition.
7. If you're using Python 3.6 or higher, try using f-strings for cleaner string formatting.
8. Remember to use the .py extension for your script—it’s good practice!
9. Add comments to your code; they can really help others (and yourself) understand your thought process.
10. Finally, try to initialize your variables closer to where they're actually used.
Keep up the good work! If you enjoy math problems, check out projecteuler.org for additional challenges.
Thanks for the detailed feedback! I’ll definitely work on implementing these tips. I just initialized the values as a habit before my GCSEs since that’s what the exam board suggests.
Why did you exclude 0 from your calculations? Remember, the square root of 0 is still 0!
Good point! I guess I overlooked that.
Oh shoot, I forgot! I’ve posted it on GitHub now.