Beginning Python: For Loop- what do to afterwards
<p>Found this exercise in a textbook online and am attempting to battle my way through it. I believe they intended it to be answered with a while loop, but I'm using a for loop instead which could be my problem.</p>

<p>"Write a program that prompts the user to enter an integer and returns two integers <em>pwr</em> and <em>root</em> such that 0 &lt; pwr &lt; 6 and root**pwr is equal to the integer entered by the user. If no such pair of integers exists, it should print "No such integers exist."</p>

<p>How can I test to see if any #s meet the criteria and if none do, say that?</p>

<pre><code>u_i = int(input("input a #:"))
root = u_i**.5

for pwr in range(1,6):
    ans = root**pwr

    if ans == u_i:
        print(pwr)
        print(int(root))
#here is where the problem comes in as it will do this every time and I'm\ failing to discover what I should do instead.
if ans!= u_i:
    print("No such integer exists")
</code></pre>

<p>Full disclosure: Its been a long time since my last math class so I'm not convinced my "solution" is even correct for what the question is asking. I'm more interested in solving the dilemma I'm facing however as I'm trying to wrap my head around using loops properly.</p>

<p>You want to check if there is an integer <code>root</code> such that <code>root ** pwr == user_input</code>. With a little math we can re-write the above statement as <code>root = user_input ** (1. / pwr)</code>. You've got a pretty small number of <code>pwr</code> values to choose from, so you can simply loop over those values (it looks like you've already got that part figured out). The last thing you need to do is (for each <code>pwr</code>) check to see if <code>root</code> is an integer, you could use <code>root % 1 == 0</code> or <code>int(root) == root</code>.</p>

<p>If you want to look "fancy" you could use python's for ... else syntax. The <code>else</code> block in a for loop only gets executed if the loop finishes without a break. For example:</p>

<pre><code>def has_dogs(pets):
    # This functions check to see if "dog" is one of the pets
    for p in pets:
        if p == "dog":
            print "found a dog!"
            break
    else:
        # This block only gets run if the loop finishes 
        # without hitting "break"
        print "did not find any dogs :("
</code></pre>

<p>The for ... else syntax is basically a fancy way to do this:</p>

<pre><code>def has_dogs(pets):
    # This functions check to see if "dog" is one of the pets
    dog_found = False
    for p in pets:
        if p == "dog":
            print "found a dog!"
            dog_found = True
            break
    if not dog_found:
        print "did not find any dogs :("
</code></pre>

python if-statement for-loop