patternpythonModerate
Quadratic equation solver in Python
Viewed 0 times
solverquadraticequationpython
Problem
I use the module
I am very interested to know if anyone has any alternatives.
os specifically for Windows since I am familiar with Batch. Batch alone didn't allow me to execute more complicated mathematical functions, I began to use Python.import os
import math
os.system('cls')
os.system('')
os.system('color a')
os.system('title Quadratic Equation Solver')
#This is used for presentation of the function for WINDOWS cmd
#------------------------------------------------
def QuadSolve():
os.system('cls')
print(" Quadratic Equation Solver 1")
print("")
print(" X = (-b +/- sqrtb^2 + sqrt4ac)/div/2a ")
print("")
print(" Quadratic equation: ax^2 + bx + c")
print("")
print("")
print("")
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? ---> "))
firstsec = -1 * b #first second and third "sectors" of the expression
secsec = math.sqrt(b ** 2 - 4 * a * c)
thirdsec = 2 * a
Plussl = firstsec + secsec #Pluss1 is where -b and root b^2 + 4ac are added to give a value of X
X = Plussl / thirdsec
Negsl = firstsec - secsec #Same purpose as Plussl but subtraction is used instead to give the other solution of X
X2 = Negsl / thirdsec
print("")
print(" X=%d OR X=%d ") % (X, X2)
os.system('pause >nul')
QuadSolve()
QuadSolve()I am very interested to know if anyone has any alternatives.
Solution
Repeating code infinitely
Right now, in order to have
The proper way to make any piece of code repeat for a variable amount is to use a
By doing this your code gains a few good things:
Integer input validation
Never trust the user to enter the correct input. For example, what if I ran your program and entered
Should be wrapped in a
Now, if a user enters incorrect input, the program will alert them to this, and start over.
Proper string formatting
The
Would become this:
-
Normal parameters:
-
Positional parameters:
-
Named parameters:
You can do a great deal more with
Getting rid of the
I find all of these lines of code to be absolutely horrid:
Especially this one in particular:
There are many things wrong here. For starters, the call to
On the matter of this line:
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:
If you're still using Python 2.x for some reason, it would look like this:
Proper style
Unlike many languages, Python has an official style guide, PEP8, and you're violating a fair amount of the guidelines set there.
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( ... ):
"""Bri
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 callsI 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, andUPPER_SNAKE_CASEif 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( ... ):
"""Bri
Code Snippets
def QuadSolver():
while True:
# Original code goes 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? ---> "))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.")print(" X=%d OR X=%d ") % (X, X2)print(" X={x1} OR X={x2}".format(x1=X, x2=X2))Context
StackExchange Code Review Q#103920, answer score: 15
Revisions (0)
No revisions yet.