5
\$\begingroup\$


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)
\$\endgroup\$
6
  • 1
    \$\begingroup\$ Note that the size of python integers is limited only by the available memory, whereas python floats have a maximum/minimum size. What size constraints did you want to place on the inputs? Note that with python's decimal and fractions modules you have a lot of flexibility to work with arbitrarily large values and manage performance, accuracy, and code complexity tradeoffs. \$\endgroup\$ Dec 27, 2020 at 16:16
  • 1
    \$\begingroup\$ There is repetition of code for input of x,e - would be nice to move it to separate function(x, e = user_input()). It is easier to see value of epsilon in scientific notation(epsilon = 1e-7). Extra comment would be nice. Camelcase -> underscores. \$\endgroup\$
    – Vashu
    Dec 27, 2020 at 22:52
  • \$\begingroup\$ Thank you @President James K. Polk I will use floats to make the code more flexibile when desired \$\endgroup\$ Dec 28, 2020 at 13:05
  • \$\begingroup\$ @Vashu thank you fro your your comment ,I will definetly do so! \$\endgroup\$ Dec 28, 2020 at 13:08
  • 2
    \$\begingroup\$ The assumption in your first if statement is false, since 0°=1. I.e. your if check and the following elif check should be switched. \$\endgroup\$ Dec 28, 2020 at 17:21

1 Answer 1

5
\$\begingroup\$

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 of x==0, e %2 == 0, x>0 and (...)/2.0.
  • snake_case should be used for function names and variables. For example, num_guesses instead of numGuesses.
  • constants should be in UPPER_CASE. For example, EPSILON = 0.000_000_1 instead of epsilon = 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 of max(1.0,x).
\$\endgroup\$
1
  • \$\begingroup\$ OMG! I never thought I can do this much simplifications to this small piece of code TY @AJNeufeld \$\endgroup\$ Dec 30, 2020 at 15:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.