I've written two functions:
is_integer()
, which tries to get a positive or a negative integer as input and returns the same value.square()
, which takes this returned value as parameter and returns square of the same.
The code in square()
uses a for
-loop that squares the integer by 'repetitive addition.' Finally, the script prints out the square of the integer returned by square()
.
Please review my code, point out errors of any kind and make suggestions.
# Squares an integer by repetitive addition
# Uses a for-loop
def square(integer):
result = 0
for element in range(1, abs(integer)+1):
result += abs(integer)
return 'Square of ' + str(integer) + ' is ' + str(result)
# Makes sure the input is an integer
def is_integer():
number = raw_input('Enter an integer: ')
if number.isdigit():
number = int(number)
return number
elif number[0] == '-' and number[1:].isdigit():
number = int(number)
return number
else:
print '%r is not an integer' % number
print 'To try again, press Enter key'
print 'Otherwise, press Ctrl+C keys to abort'
raw_input('>>> ')
return is_integer()
# Square() takes as parameter the value returned by is_digit()
# Print the result returned by square()
print square(is_integer())