I'm new to programming and python,this one of my biggest codes in python yet...
I just wanted to know if you can simplify it further...
English is not my first language, so corrections in the language are also welcomed!
Thank You In advance!
x = int(input('Enter an integer who\'s root value you need: '))
e = int(input('Enter an +ve integer for root value: '))
#Removing the possiblities of zero in eihter of the variables
if x==0:
print('Zero power anything is zero!')
elif e==0:
print('Anything power zero is one!')
else:
while e < 0:
print('I SAID +VE INTEGER FOR ROOT!')
x = int(input('Enter an integer who\'s root value you need: '))
e = int(input('Enter an +ve integer for root value: '))
while e %2 == 0 and x < 0:
print('-ve nos. can\'t have root value for even roots!')
x = int(input('Enter an integer who\'s root value you need: '))
e = int(input('Enter an +ve integer for root value: '))
epsilon = 0.0000001
numGuesses = 0
if x>0:
low = -x
elif x<0:
low = x
if x>0:
high = max(1.0,x)
elif x<0:
high = max(1.0,-x)
ans = (high + low)/2.0
while abs(ans**e - x) >= epsilon:
print('low =', low, 'high =', high, 'ans =', ans)
numGuesses += 1
if ans**e < x:
low = ans
else:
high = ans
ans = (high + low)/2.0
print('numGuesses =', numGuesses)
print(ans, 'is close to the value of', e, 'root', x)
1 Answer 1
Ignoring points already made in comments...
Escapes
x = int(input('Enter an integer who\'s root value you need: '))
I find reading this line of code jarring. There is an escape \'
in the middle of the string. Python gives many different types of literal strings with allow you to embed special characters in strings without using escapes. At the simplest end of the spectrum, a double-quoted string will allow you to embed a single quote without an escape.
x = int(input("Enter an integer who's root value you need: "))
There are also triple-quoted strings """..."""
or '''...'''
both of which will allow you to embed unescaped single and double quotes, as well as new lines. You don't need this here, but it is good to be aware of.
Input Validation
Your validation has holes.
At the first pair of prompts, enter "1" and "-1". This causes you to enter the while e < 0:
loop, where you can enter another pair, like "-1" and "2". This will cause you to enter the while e %2 == 0 and x < 0:
loop, where you can enter "0" and "0".
At this point, x
is neither greater than or less than zero, so neither low
nor high
are assigned a value, causing an exception at ans = (high + low)/2.0
You want the earlier tests to be repeated for the new inputs. This is easiest achieved with a single while loop around the input.
while True:
x = int(input("Enter an integer who's root value you need: "))
e = int(input("Enter an +ve integer for root value: "))
if e < 0:
print("I SAID +VE INTEGER FOR ROOT!")
elif e % 2 == 0 and x < 0:
print("-ve nos. can't have root value for even roots!")
else:
# The input is now good, exit the while-loop.
break
if x==0:
print("Zero power anything is zero!")
elif e==0:
print("Anything power zero is one!")
else:
epsilon = 0.0000001
numGuesses = 0
...
Now, the input is requested. If it fails either test, the while
loop repeats, and all the validation checks are repeated with the new input.
Exceptions
If the user enters a non-integer value, int(...)
will raise an ValueError
exception. You could be kind and capture that as well.
while True:
try:
x = int(input("Enter an integer who's root value you need: "))
e = int(input("Enter an +ve integer for root value: "))
if e < 0:
print("I SAID +VE INTEGER FOR ROOT!")
elif e % 2 == 0 and x < 0:
print("-ve nos. can't have root value for even roots!")
else:
# The input is now good, exit the while-loop.
break
except ValueError:
print("Only integer values are permitted.")
if x == 0:
...
...
Unnecessary conditionals
if x>0:
low = -x
elif x<0:
low = x
if x>0:
high = max(1.0,x)
elif x<0:
high = max(1.0,-x)
You are testing x>0
, x<0
, x>0
, and x<0
. We can remove half of these, by combining the two if-elif statements:
if x>0:
low = -x
high = max(1.0,x)
elif x<0:
low = x
high = max(1.0,-x)
This is arguably clearer. But the second test, x<0
is unnecessary. We've already checked for x == 0
earlier, and now have just tested x>0
. The only other possibility is x < 0
, so we can get away with just an else:
if x>0:
low = -x
high = max(1.0,x)
else:
low = x
high = max(1.0,-x)
PEP 8
The Style Guide for Python Code lists many conventions which Python programs should follow, for maximum readability by other Python programmers.
- Binary operators should be surrounded by one space. For instance, you should write
x == 0
,e % 2 == 0
,x > 0
and(...) / 2.0
instead ofx==0
,e %2 == 0
,x>0
and(...)/2.0
. snake_case
should be used for function names and variables. For example,num_guesses
instead ofnumGuesses
.- constants should be in
UPPER_CASE
. For example,EPSILON = 0.000_000_1
instead ofepsilon = 0.0000001
if the value never changes. - Use
_
in long numerical constants to group digits for easier readability, as in above example. - Commas should be followed by a space. For instances,
max(1.0, x)
instead ofmax(1.0,x)
.
-
\$\begingroup\$ OMG! I never thought I can do this much simplifications to this small piece of code TY @AJNeufeld \$\endgroup\$Madhoora Mohan S– Madhoora Mohan S2020年12月30日 15:31:04 +00:00Commented Dec 30, 2020 at 15:31
decimal
andfractions
modules you have a lot of flexibility to work with arbitrarily large values and manage performance, accuracy, and code complexity tradeoffs. \$\endgroup\$if
statement is false, since 0°=1. I.e. yourif
check and the followingelif
check should be switched. \$\endgroup\$