Fred James
Fred James

Reputation: 65

Prevent certain numbers from printing

Sorry for the bad title. Here is my code:

import math
# Finds the square root of a number
def square_root():
    square_root = math.sqrt(int(raw_input('What number do you want the Square Root for')))
    print "The square root of is: %d " % (square_root)

Basically, I want to prevent the user from entering a number which doesn't end in 0, 1, 4, 6, 9 or 25 so I can only output perfect squares. I sort of have an idea of what to do but I can't for the life of me recall the terminology to get a decent Google search going so I came here.

I know it will involve some form of if and something that looks like this [1:3].

Upvotes: 2

Views: 151

Answers (3)

arshajii
arshajii

Reputation: 129537

If you want to make sure the input is a perfect square, try something like this:

def square_root():
    sqrt = int(raw_input("What number do you want the square root for? ")) ** 0.5
    if sqrt == int(sqrt):  # i.e. 'sqrt' is an integer
        print "Result is", int(sqrt)
    else:
        print "That is not a perfect square!"

Just checking if the input ends in the numbers you mentioned will not be sufficient (as one of the comments mentioned). Of course, if you still wanted to check that you could just use str(input).endswith(SOME_VAL).

Upvotes: 4

Dr. Jan-Philip Gehrcke
Dr. Jan-Philip Gehrcke

Reputation: 35756

First of all, read your input to a string. Then, test your string for certain endings with the s.endswith('test') method. If successful, convert the input to an integer while expecting a ValueError to happen (catch this one with a try/except ValueError: statement). If everything went well, calculate the square root and print it.

Your test on certain endings does not make sense mathematically. But that is a different topic. Let's use your request as programming exercise :) This code (untested) hopefully does what you want:

import sys
import math

tests = ['0', '1', '4', '6', '9', '25']
input = raw_input('What number do you want the square root for? ')
result = (input.endswith(t) for t in tests)
if any(result):
    try:
        print math.sqrt(int(input))
    except ValueError:
        print "Not a number."

(input.endswith(t) for t in tests) is a generator expression. It does not return a list, rather it returns an iterable object, also called iterator. This is what result is. The elements in result are only computed when requested. any(result) goes through this sequence and requests one test result after the other until it finds the first that evaluates to True. It then returns True itself. If all of the values in the result sequence are False, also any() returns False.

Upvotes: 2

Fredrik Pihl
Fredrik Pihl

Reputation: 45672

>>> a=map(int,str(123456))

>>> a
[1, 2, 3, 4, 5, 6]

>>> a[-1]
6

>>> a[-1] in [0, 1, 4, 6, 9, 25]
True

Upvotes: 1

Related Questions