Type a function that gets an input of two whole numbers and returns their multiplication result, with no use of mathematical operations other than addition.
Type a function that gets an input of two numbers, and returns the result of the first to the power of the second, mathematical operations are not allowed at all, it is allowed and even recommended to use the function from the previous exercise.
Now 18. is pretty straightforward, I did it:
def multiplication_of_numbers(first_num, second_num):
result = 0
for repetition in range(first_num):
result += second_num
return result
first_number = int(input('type in the first number > '))
second_number = int(input('type in the second number > '))
print(f'{first_number} multiplied by {second_number is {multiplication_of_numbers(first_number,second_number)}')
However I can't seem to find out how to use multiplication in order to get the power using the same two numbers. Maybe I'm missing something.
I tried to find the mathematical relation between the result of a multiplication and the result of the Exponentiation but I found none. Also couldn't figure out how to do it with "mathematical operations are not allowed at all"
To complete this task, you should use your multiplication_of_numbers
function in a new function to get the result of an exponential expression.
def multiplication_of_numbers(first_num, second_num):
result = 0
for _ in range(first_num): # it is convention to use _ if the value is not used
result += second_num
return result
def power(base, exponent):
result = 1 # 0^n = 0 => 1 must be used instead of 0
for _ in range(exponent):
result = multiplication_of_numbers(result, base)
return result
def main():
try:
print('type in the first number > ', end='')
first_number = int(input())
print('type in the second number > ', end='')
second_number = int(input())
print(f'{first_number}^{second_number} = {power(first_number,second_number)}')
except ValueError:
print('An invalid input was given.') # In case the input cannot be converted to an integer value
if __name__ == '__main__':
main()