Repeating code infinitely
Right now, in order to have QuadSolver
repeat forever, you're calling it recursively, by calling QuadSolver
again inside of itself. Unlike functional languages, which are optimized for tail-call recursion, Python isn't. Once you've recursed in the same function 1000 times, Python will raise an error. You can technically set the recursion limit using sys.setrecursionlimit
, but this is a very "hacky" way to do things.
The proper way to make any piece of code repeat for a variable amount is to use a while
loop. This means that the body of your QuadSolver
function should be wrapped in a while
loop, like this:
def QuadSolver():
while True:
# Original code goes here.
By doing this your code gains a few good things:
- It will properly execute forever.
- It's faster.
- It's more readable, e.g, it's clear to the reader that you're executing a chunk of code forever.
Integer input validation
Never trust the user to enter the correct input. For example, what if I ran your program and entered asghiopisdfiojgpfdj
for the variable a
? Your program would raise a ValueError
and crash. You need to use a try
/except
block to catch a ValueError
in case the user enters the wrong input. This means that this section of code here:
a = int(input(" What is the value of a? ---> "))
b = int(input(" What is the value of b? ---> "))
c = int(input(" What is the value of c? ---> "))
Should be wrapped in a try
/except
block, like this:
try:
a = int(input(" What is the value of a? ---> "))
b = int(input(" What is the value of b? ---> "))
c = int(input(" What is the value of c? ---> "))
# Original code below the above section goes here.
except ValueError:
print("Please enter a valid integer.")
Now, if a user enters incorrect input, the program will alert them to this, and start over.
Proper string formatting
The %
operator is deprecated as of Python 2.6. Instead, you should be using the str.format
function instead. For example, this line:
print(" X=%d OR X=%d ") % (X, X2)
Would become this:
print(" X={x1} OR X={x2}".format(x1=X, x2=X2))
str.format
supports the following styles:
Normal parameters:
"{} {}".format("Hello", "world")
Positional parameters:
"{1} {0}".format("world", "Hello")
Named parameters:
"{word1} {word2}".format(word1="Hello", word2="world")
You can do a great deal more with str.format
, but I'll leave it up to you to figure that out, as there's too much for this one post.
Getting rid of the system
calls
I find all of these lines of code to be absolutely horrid:
os.system('cls')
os.system('')
os.system('color a')
os.system('title Quadratic Equation Solver')
os.system('pause >nul')
Especially this one in particular:
os.system('pause >nul')
There are many things wrong here. For starters, the call to os.system
has a long startup and "cooldown" period, e.g, it takes a fair amount of time. Secondly, all the commands you're running, like cls
, color
, or pause
are very Windows-specific. What happens if someone wants to run this on a Linux-based system? Most of these system
calls are purely stylistic, and unnecessary anyways.
On the matter of this line:
os.system('pause >nul')
I find it awful that bad C++ practices are leaking into Python. The method above is slow, insecure, and unreadable. If you want to pause until user input, just use the standard input operations of your language. In the case of Python, that would just look like this:
input()
If you're still using Python 2.x for some reason, it would look like this:
raw_input()
Proper style
Unlike many languages, Python has an official style guide, PEP8, and you're violating a fair amount of the guidelines set there.
- Variable names should be in
snake_case
, and UPPER_SNAKE_CASE
if they're constants.
- Function names should only be in
snake_case
.
- Classes should be in
PascalCase
.
- You should have two spaces between top-level code/functions/classes.
While the following items aren't actually in PEP8, they're kind of a code smell, and should be removed.
Separator comments, like the one below this should be removed. They're useless and look bad in your code.
#------------------------------------------------
Inline comments on the end of code lines should be removed. If you're having to put comments on the end of lines of code, then you probably aren't writing the code in a clear enough way. If you feel the need to put comments at the end of lines of code, then chances are, those lines should be re-written.
It's also worth mentioning docstrings as well. Docstrings are a convenient way to describe your functions and classes in Python, much like XML documentation in Visual Studio. A typical function docstring generally looks something like this:
def my_function( ... ):
"""Brief description of the function.
Detailed description of the function.
argument_name -- Argument description.
"""
If we take this and apply it to your QuadSolver
function, we get something like this:
def quad_solver():
"""Solve the quadratic equation.
This function takes user input, a, b, and c, and
runs it through the quadratic equation to "solve"
it.
"""
...
better
? In terms of coding alternatives, prettier, imho, see this \$\endgroup\$