python 3.x - Recursive Function to Calculate Exponential without " * " -
write function power accepts 2 arguments, , b , calculates raised power b. example: power(2,3) = 8 raise typeerror message argument must integer or float if inputs other ints or floats. note: don't use **
my code below not given me desired output. please wrong?
def power(a, b): if == type(int) or == type(float) , b == type(int) or b == type(float): def add(a, b): num = in range(b): num += 1 return num def multiply(a, b): num = 0 in range(b): num = add(num, a) return num def power(a, b): num = 1 in range(b): num = multiply(num, a) return num else: return "argument must integer or float"
there bunch of issues code.
to start with, type checking fractally wrong (it keeps getting more wrong more it). should use isinstance(a, (int, float)) , isinstance(b, (int, float)) rather backwards stuff have now. you're checking if a , b equal class type (which type of int , float). have expression grouping wrong, and operator binds more tightly ors (your code a or (b , c) or d when wanted (a or b) , (c or d)).
next, you're defining new functions do power calculation, never call them outer power function (so they'll never anything). if want keep inner functions, need return power(a, b) call somewhere. simplify things bunch getting rid of inner functions , doing computation directly in nested loops. nested functions necessary.
you're not doing you're supposed in error case. you're supposed raise typeerror, not return string.
and finally, think you've made whole problem more complicated necessary. assignment says not use **, suspect you're still allowed use * , + operators. i'd multiplying in loop rather redefining ground (which doesn't work, since add function needs +=).
one further note: problem statement doesn't if b (the exponent) going whole number, or if can have fractional part. handling fractional exponents lot more difficult handling whole number exponents, i'd ask instructor if that's part of assignment before spending lot of time on trying solve it. may need support both int , float types, if b float still whole number.
Comments
Post a Comment