Introduction to Computing and Programming Using Python

I am trying to solve Finger Exercise 3.1 and I cannot figure out what I am doing wrong here. When I enter "1" as an integer, it returns 0 and 0.

I'm a complete newbie to programming and stack overflow, so I'm not sure if I'm doing it right, but figured I'd do it.

This is the problem: Write a program that asks the user to enter an integer and prints two integers, root and pwr, such that 0 <pwr <6 and root ** pwr is equal to the integer entered by the user. If no such pair of integers exists, it should print this effect message.

And here is my solution:

x = int(raw_input('Enter a positive integer: '))
root = 0
pwr = 0
while pwr < 6:
    pwr += 1
    while root**pwr < x:
        root += 1
if root**pwr == x:
    print "The root is " + str(root) + " and the power is " + str(pwr)
else:
    print "No such pair of integers exists."

      

How can I fix my code so that it returns correct integers? What am I doing wrong here? What logic am I missing?

+3


source to share


2 answers


While this is not very idiomatic in Python, you are close to the correct answer.

The first problem is that you never reset root

, so you will only execute the inner loop once. Moving root = 0

to the outer loop needs to be fixed.

The second mistake is that you never break the loop when you hit the condition you want. Moving the test inside the loop will fix this.

Let's see how we do it:



x = int(raw_input('Enter a positive integer: '))
pwr = 0
while pwr < 6:
    root = 0
    pwr += 1
    while root**pwr < x:
        root += 1
        if root**pwr == x:
            print "The root is {} and the power is {}".fornat(
               root, pwr
            )
else:
    print "No such pair of integers exists."

      

Output:

Enter a positive integer: 16
The root is 16 and the power is 1
The root is 4 and the power is 2
The root is 2 and the power is 4
No such pair of integers exists.

      

Since this is a learning exercise, I will let you understand and fix other problems with your code.

+1


source


One problem is that although you have conditions that end your loops, they will always go up to the maximum condition allowed. You can solve this with, break

or, as shown, with return

in a function. Also, instead of using a counter, use a function xrange()

( range()

in Python 3).



>>> def p(num):
...     for power in xrange(6):
...         for root in xrange(num/2+1):
...             if root**power==num:
...                 return root, power
...
>>> r, pwr = p(8)
>>> print 'The root is', r, 'and the power is', pwr
The root is 2 and the power is 3

      

+2


source







All Articles