I'm trying to write a program as an exercise to calculate the integral value from a to b with one of 2 mathematical functions. My function integrate should have f as the mathematical function to integrate.
from math import *
def g(x):
return float(x) * float(x) + 3
def h(x):
return math.cos(float(x) * float(x))
def integrate(f, a, b, n):
H = (abs(float(a) - float(b)))/float(n)
ans = 0
xWaarde = a - H/2
print xWaarde
for k in range(1, n+1):
xWaarde = xWaarde + H
ans = ans + f(xWaarde) * H
return ans
print 'available functions:'
print 'g(x) = x^2+3'
while True:
print 'h(x) = cos(x^2)'
aIn = float(raw_input('integral from a = '))
bIn = float(raw_input('to b = '))
nIn = int(raw_input('Number of subintervals: '))
while True:
funcIn = raw_input('Which function do you want to use? (g or h): ')
if funcIn == 'g':
integrate(g,aIn,bIn,nIn)
break
elif funcIn == 'h':
integrate(h,aIn,bIn,nIn)
break
else:
print 'This function is not available'
print 'The definite integral is', integrate(funcIn, aIn, bIn, nIn)
doorg = raw_input('Do you want to continue? (y or n): ')
if doorg == 'n':
break
else:
print
The full Traceback is as follows:
Traceback (most recent call last):
File "C:/Users/Nick van Stijn/Desktop/Python/Assignment 3.1.py", line 38, in <module>
print 'The definite integral is', integrate(funcIn, aIn, bIn, nIn)
File "C:/Users/Nick van Stijn/Desktop/Python/Assignment 3.1.py", line 16, in integrate
ans = ans + f(xWaarde) * H
TypeError: 'str' object is not callable
EDIT: SOLVED
I made a mistake by calling a function at a time I didn't have to call it at all.
The problem is that you call integrate using the proper function, f or g, but then discard the result and instead call integrate again for the print, this time passing just the name of the function, funcIn.
Instead, you should just store the result in a variable, e.g., like this:
result = None
while result is None:
funcIn = raw_input('Which function do you want to use? (g or h): ')
if funcIn == 'g':
result = integrate(g,aIn,bIn,nIn)
elif funcIn == 'h':
result = integrate(h,aIn,bIn,nIn)
else:
print 'This function is not available'
print 'The definite integral is', result
Also, you could use a dict to map function names to actual functions, instead of using a possibly large number of if/elif/else:
functions = {'h': h, 'g': g}
while result is None:
funcIn = raw_input('Which function do you want to use? (g or h): ')
if funcIn in functions:
result = integrate(functions[funcIn],aIn,bIn,nIn)
else:
print 'This function is not available'
You are using the textual name of the function in the form of a string, rather than a reference to the function object itself. While there are hacky techniques to derive the function object from a string name, they can difficult to maintain and error-prone. Since in python functions are objects like any other (so called "first-class" objects) they are not really named, only references to functions have names.
This is a good example where a dictionary comes in handy, particularly if you wish to add more functions later. We can map a text key (what the user enters) to any python object, including a function:
from math import *
def g(x):
return float(x) * float(x) + 3
def h(x):
return math.cos(float(x) * float(x))
# Store references to the functions in a dictionary
# with the keys as the text name (the names need not match)
funcs = {'g': g, 'h': h} # <<<< ADDED
def integrate(f, a, b, n):
H = (abs(float(a) - float(b)))/float(n)
ans = 0
xWaarde = a - H/2
print xWaarde
for k in range(1, n+1):
xWaarde = xWaarde + H
ans = ans + f(xWaarde) * H
return ans
print 'available functions:'
print 'g(x) = x^2+3'
while True:
print 'h(x) = cos(x^2)'
aIn = float(raw_input('integral from a = '))
bIn = float(raw_input('to b = '))
nIn = int(raw_input('Number of subintervals: '))
while True:
funcIn = raw_input('Which function do you want to use? (g or h): ')
# THIS CODE CHANGED - note the simplification
# we just test for membership of the dictionary
if funcIn in funcs:
integrate(funcs[funcIn],aIn,bIn,nIn)
break
else:
print 'This function is not available'
# THIS CODE CHANGED (note first argument to integrate)
print 'The definite integral is', integrate(funcs[funcIn], aIn, bIn, nIn)
doorg = raw_input('Do you want to continue? (y or n): ')
if doorg == 'n':
break
else:
print
Related
I'm currently coding a simplified RSA algorithm for a project at school but can't get it to work.
I've based the code off of the formulae c = m^e(mod N) and (c^d)mod N. The encryption function works to produce what looks like a feasible output but when I put it into the decryption function it either doesn't return the message correctly or gives me this error:
ValueError: chr() arg not in range(0x110000)
My code:
import random
import math
def is_prime(x):
for i in range(2,int(math.sqrt(x))+1):
if x % i == 0:
return False
break
return True
def gcd(a, b):
if (b == 0):
return a
else:
return gcd(b, a % b)
def generate_p_and_q(p,q):
p_and_q = []
p_and_q.append(p)
p_and_q.append(q)
return p_and_q
def generate_phi(p,q):
p_and_q = generate_p_and_q(p,q)
phi = (p_and_q[0] - 1)*(p_and_q[1] - 1)
return phi
def generate_N(p,q):
p_and_q = generate_p_and_q(p,q)
N = (p_and_q[0])*(p_and_q[1])
return N
def generate_e(p,q):
phi = generate_phi(p,q)
with open('First500Primes.txt') as f:
lines = f.read().splitlines()
for i in lines:
if int(i) > 1 and int(i)< phi:
if gcd(int(i), phi) == 1:
e = int(i)
break
return e
def encrypt_RSA():
encrypted = []
message = input("Enter a message to encrypt:")
message.lower()
with open('First500Primes.txt') as f:
lines = f.read().splitlines()
valid = False
choice = input("Do you want to: \nA: enter a key \nB: use a random key?\n")
if choice.lower() == 'a':
p = int(input("Enter a key - this must be a prime number between 0 and 500:"))
q = int(input("Enter a key - this must be a prime number between 0 and 500:\n"))
while valid != True:
valid = is_prime(p) and is_prime(q)
if valid == False:
print("Your numbers were not prime!")
p = int(input("Enter a key - this must be a prime number between 0 and 500:"))
q = int(input("Enter a key - this must be a prime number between 0 and 500:\n"))
else:
x = random.randint(0, 499)
y = random.randint(0, 499)
p = int(lines[x])
q = int(lines[y])
generate_p_and_q(p,q)
e = generate_e(p,q)
N = generate_N(p,q)
for char in message:
encrypted.append((ord(char) ** e) % N)
result = ''
for i in encrypted:
result = result + str(i)
print("encrypted message: " + result)
info = [encrypted, N, e]
return (info)
encrypt_RSA()
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def calculate_d(a,m):
g,x,y = egcd(a,m)
if g != 1:
return None
else:
return x%m
def calculate_phi(N):
with open('First500Primes.txt') as f:
lines = f.read().splitlines()
for num in lines:
if N%int(num) == 0:
p = int(num)
q = N/int(num)
phi = (p-1)*(q-1)
return int(phi)
def decrypt_RSA():
encrypted = encrypt_RSA()
encrypted_message, N, e = encrypted[0], encrypted[1], encrypted[2]
print(N)
phi = calculate_phi(N)
d = calculate_d(phi,e)
print("D: " + str(d))
message = []
encrypted_message = (encrypted[0])
for c in encrypted_message:
m = (c**d) % N
print(m)
message.append(chr(m))
print(message)
decrypt_RSA()
I need the code to firstly encrypt the message with the encrypt function then decrypt it with the decrypt function, so the encrypted and original message should be displayed.
Could someone tell me whats wrong with my code (since I'm still in school, it may need to be simplified), any additional feedback would be greatly appreciated.
After a bit of debugging, the problem is that the function calculate_d() does not seem to calculate the right number. It is solved when we invert the params of one of your function. Change this line
d = calculate_d(phi, e)
to this:
d = calculate_d(e, phi)
That got it working for me.
Also, since you asked for suggestions to improve your code, I made a few (a lot) improvements. Some ideas:
I replaced the parts that read the prime number file with a prime number generator, but that is just because I didn't have the file at hand. Choose whichever you like best.
Invoke the main functions inside a if __name__ == '__main__':. Read about it here.
I moved the input prompts outside of the encryption code. Implement those parts as needed (random or prompting user for input) and just pass the result to the function for encryption.
My version:
def generate_primes():
"""
Generate an infinite sequence of prime numbers.
Sieve of Eratosthenes
Code by David Eppstein, UC Irvine, 28 Feb 2002
http://code.activestate.com/recipes/117119/
https://stackoverflow.com/a/568618/9225671
"""
# Maps composites to primes witnessing their compositeness.
# This is memory efficient, as the sieve is not "run forward"
# indefinitely, but only as long as required by the current
# number being tested.
D = {}
# The running integer that's checked for primeness
q = 2
while True:
if q not in D:
# q is a new prime.
# Yield it and mark its first multiple that isn't
# already marked in previous iterations
yield q
D[q * q] = [q]
else:
# q is composite. D[q] is the list of primes that
# divide it. Since we've reached q, we no longer
# need it in the map, but we'll mark the next
# multiples of its witnesses to prepare for larger
# numbers
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1
def choose_p_and_q():
p_i = random.randint(0, 100)
q_i = random.randint(0, 100)
p = 0
q = 0
for i, n in enumerate(generate_primes()):
if i <= p_i:
p = n
if i <= q_i:
q = n
if i > p_i and i > q_i:
break
return p, q
def generate_n(p, q):
return p * q
def generate_phi(p, q):
return (p - 1) * (q - 1)
def generate_e(phi):
e = None
for n in generate_primes():
if math.gcd(n, phi) == 1:
e = n
if n >= phi:
if e is None:
raise ValueError('no suitable prime number found; reached {}'.format(n))
# return the highest prime number found
return e
def find_p_and_q_from_n(n):
for i in generate_primes():
if n % i == 0:
p = i
q, remainder = divmod(n, p)
if remainder == 0:
return p, q
def egcd(a, b):
if a == 0:
return b, 0, 1
else:
g, y, x = egcd(b % a, a)
return g, x - (b // a) * y, y
def calculate_d(phi, e):
g, x, _ = egcd(phi, e)
if g == 1:
return x % e
raise ValueError('no modular multiplicative inverse found')
def encrypt_rsa(msg):
p, q = choose_p_and_q()
n = generate_n(p, q)
phi = generate_phi(p, q)
e = generate_e(phi)
print()
print('ENCRYPT')
print('p ', p)
print('q ', q)
print('n ', n)
print('phi ', phi)
print('e ', e)
encrypted_list = []
for char in msg:
m = (ord(char) ** e) % n
encrypted_list.append(m)
print('msg ', list(msg))
print('encrypted_list', encrypted_list)
return encrypted_list, n, e
def decrypt_rsa(encrypted_list, n, e):
p, q = find_p_and_q_from_n(n)
phi = generate_phi(p, q)
d = calculate_d(e, phi)
print()
print('DECRYPT')
print('p ', p)
print('q ', q)
print('n ', n)
print('phi ', phi)
print('e ', e)
print('d ', d)
decrypted_list = []
for elem in encrypted_list:
m = (elem**d) % n
decrypted_list.append(chr(m))
print('decrypted_list', decrypted_list)
if __name__ == '__main__':
msg = input('Enter a message to encrypt:').strip()
data = encrypt_rsa(msg)
decrypt_rsa(*data)
I have been curious about how to simplify my work. But for now, my
problem is how to pass variables through functions and to get this If
statement to work. The variable a and b need to pass into the if
statement to check if the string is in the array 'colors' or
'other_colors'
import random;
hot_spot=0;
colors = ['R','G','B','O','P']
other_colors =['RED','GREEN','BLUE','ORANGE','PURPLE']
guesser_array=[]
def code_maker():
code_maker_array=[]
for i in range(4):
ran = random.randint(0,4)
print (ran)
code_maker_array.append(colors[ran])
print(code_maker_array)
return code_maker_array
x = code_maker()
def code_breaker():
trys = 0;
cbi = input('please put in r,g,b,o,p or red,green,blue,orange,purple_ ')
cbi = cbi.upper()
if ( isinstance(cbi,str) == True):
print ('it is a string')
print (cbi)
for i in range(4):
if (len(cbi)>=3):
a = other_colors[i].find(cbi)
else:
b = colors[i].find(cbi)
if (a >= 0 or b >= 0):
print ('yummmeiabui aebfiahfu dsdsde')
y = code_breaker()
"""
def code_checker(x):
print (x)
code_checker(x)
"""
Try this:
import random
hot_spot=0
colors = ['R','G','B','O','P']
other_colors =['RED','GREEN','BLUE','ORANGE','PURPLE']
guesser_array=[]
def code_maker():
code_maker_array=[]
for i in range(4):
ran = random.randint(0,4)
print (ran)
code_maker_array.append(colors[ran])
print(code_maker_array)
return code_maker_array
x = code_maker()
def code_breaker():
trys = 0;
cbi = input('please put in r,g,b,o,p or red,green,blue,orange,purple_ ')
cbi = cbi.upper()
if ( isinstance(cbi,str) == True):
print ('it is a string')
print (cbi)
for i in range(4):
a=b=0 #This line added
if (len(cbi)>=3):
a = other_colors[i].find(cbi)
else:
b = colors[i].find(cbi)
if (a >= 0 or b >= 0):
print ('yummmeiabui aebfiahfu dsdsde')
y = code_breaker()
"""
def code_checker(x):
print (x)
code_checker(x)
"""
The variables a and b you have defined run out of scope as soon as their respective if blocks end. To prevent this, you can simply define them by initializing them to 0 (or any other value) outside of the if statement.
While Lucefer's answer simplified code a lot, I added this because defining variables in an outer scope like this is and modifying their values later on (in the if blocks in your case) is a very common practice, you might find it helpful somewhere else as well.
remove this whole code segment
for i in range(4):
if (len(cbi)>=3):
a = other_colors[i].find(cbi)
else:
b = colors[i].find(cbi)
if (a >= 0 or b >= 0):
print ('yummmeiabui aebfiahfu dsdsde')
just simply add
if( (cbi in other_colors) or (cbi in colors) ):
print ('yummmeiabui aebfiahfu dsdsde')
Before asking my question, I'll explain what this short piece of code exactly does: first you get a menu where you can make a choice, if you choose 1, it should ask for the watch time (W) views (V) then for the duration of the video (h),(m) and (s). But now when you choose 1 it gives me this error:
Traceback (most recent call last):
File "C:/Users/Arcky/Desktop/youtube-avarage-watch-time-v2 help.py", line 72, in <module>
main()
File "C:/Users/Arcky/Desktop/youtube-avarage-watch-time-v2 help.py", line 65, in main
getchoice(Choice)
NameError: name 'Choice' is not defined
so far I can see is Choice defined in the function called choice()
maybe I should use a different name?
If you can help to fix this and let it work, I would be really grateful
here's the full code
def menu():
print('make your choice')
print('1. calculate Av. view duration')
print('2. end this shit')
def choice():
Choice = 0
Choice = (int(input('make a choice... ')))
while Choice <= 0 or Choice >= 3:
print('Error!')
Choice = (int(input('make a choice... ')))
return Choice
def getchoice(Choice):
if Choice == 1:
print(Choice)
getwatchtimeandviews()
def getwatchtimeandviews():
W =int(input("Enter Watch Time: "))
V =int(input("Enter Views: "))
return W, V
def gettimeofvideo():
h =int(input("Enter hours:"))
m =int(input("Enter minutes:"))
if m >=60:
m = m-60
h = h + 1
s =int(input("Enter seconds:"))
if s >=60:
s = s-60
m = m + 1
if m >=60:
m = m-60
h = h + 1
return h, m, s
def calculateviewduration(W,V,h,m,s):
A = W / V
As = A*60
T = (h*3600) + (m*60) + s
P = (As/T)*100
Am = 0
return
def checkinput(As, P, Am):
if As <= 59:
print('Av. view duration:',round(As),'sec','(',round(P,2),'%)')
while As > 59:
Am = Am + 1
As = As - 60
print('Av. view duration:',round(Am),'min', round(As),'sec','(',round(P,2),'%)')
if P > 100:
print('error! value cannot be higher then 100%!')
def stop():
print()
def main():
menu()
choice()
getchoice(Choice)
print ("Enter duration of video:")
gettimeofvideo()
calculateviewduration(W,V,h,m,s)
if __name__ == '__main__':
main()
You should to learn scope of variable.
For example, you defined a choice function, and defined a Choice variable in the choice function, then the Choice variable will effect only in the choice function.
If you want to let some variables effect global, you can define the variable out of funtions, or add global keyword when you define(like global Choice)
The Choice variable you declared is limited to choice function only. If you want to use it globally make it global or define at the top most indentation level
Pretty noob question so please bear with me because I am new to Python. Below given code is about Ordinary Differential Equation generating automatic combinations of ODE. I tried to execute this code on Python 3.6.3 and on Spider(Pyton 3.6) but no outcomes. I spent many days to make it executable on new version of Python but I am unable to execute it because more errors are generating. So I copied the code as it was.
from scipy import*
from scipy.integrate import odeint
from operator import itemgetter
import matplotlib
matplotlib.use('Agg')
from matplotlib.ticker import FormatStrFormatter
from pylab import *
from itertools import product, islice
from numpy import zeros_like
from string import ascii_lowercase
import operator
import sys
t_range = arange(0.0, 20.0, 0.1)
# initial_condi = []
# VarList = []
# ParamsList = []
ops = "+-"
opsdict = { "+": operator.add, "-": operator.sub }
# if len(initial_condi)!=len(VarList):
# sys.exit('error: the number of initional conditions do not equal to the number of variables')
def odeFunc(Y, t, model, K):
return GenModel(Y, model, K)
def GenModel(Y, model, K):
# New array of floating-point zeros the size of Y
dydt = zeros_like(Y)
for i, derivative in enumerate(model):
for j, operator in enumerate(derivative):
# Sequentially compute dy/dt for each variable in Y
dydt[i] = opsdict[operator](dydt[i],K[j]*Y[j])
return dydt
# Returns a nicer-looking string for a derivative expression given the encoding
def derivString(vars, deriv):
result = ""
for i, v in enumerate(vars):
if i == 0 and deriv[i] == '+':
result += v
else:
result += deriv[i]+v
return result
# main
numvars = int(raw_input("Enter number of variables\n> "))
VarList = ascii_lowercase[:numvars]
nummodels = (2**numvars)**numvars
# begin looping
input = ""
while input != "quit":
print "\n%d possible models" % nummodels
input = raw_input("Enter model ID (zero-indexed) or 'quit'\n> ")
# Basic input filtering
if input == "quit":
continue
elif not input.isdigit():
print "Input must be a non-negative integer"
continue
ID = int(input)
if ID >= nummodels or ID < 0:
print "Invalid ID"
continue
# itertools.product creates a generator for all possible combinations of +-
derivatives = product(ops, repeat=numvars)
# We take the product again to generate all models
models = product(derivatives, repeat=numvars)
# islice takes the specified model
model = next(islice(models, ID, None))
# Display dy/dt for each variable
print "Model %d:" % ID
IDtitle = []
for i, variable in enumerate(VarList):
tempstring = "d%c/dt = %s" % (variable, derivString(VarList, model[i]))
IDtitle.append(tempstring)
print "\t" + tempstring
# User specifies the initial values of all variables.
# This process can be automated but this is to demonstrate that the progam
# accepts any input
init_cons = []
params = []
confirm = ""
while confirm not in ("y", "n"):
confirm = raw_input("Run this model? (y/n)\n> ")
if confirm == "n":
continue
print "\nEnter <initial value, parameter> pairs separated by ','"
for i, variable in enumerate(VarList):
iv_param = map(float, raw_input("> %c: " % variable).split(','))
init_cons.append(iv_param[0])
params.append(iv_param[1])
print "\nRunning ODEint...",
result = odeint(odeFunc, init_cons, t_range, args=(model,params))
print " done."
print "Plotting results...",
f = figure(ID)
title(", ".join(IDtitle))
for i, variable in enumerate(VarList):
plot(t_range, result[:,i], label=variable)
legend()
axhline(0, color='k')
savefig("model"+str(ID))
close(f)
print "done."
print " -- Bye --"
raw_input is now called input in Python3. You also had a variable called input, which may have caused confusion.
from scipy import *
from scipy.integrate import odeint
from operator import itemgetter
import matplotlib
matplotlib.use('Agg')
from matplotlib.ticker import FormatStrFormatter
from pylab import *
from itertools import product, islice
from numpy import zeros_like
from string import ascii_lowercase
import operator
import sys
t_range = arange(0.0, 20.0, 0.1)
# initial_condi = []
# VarList = []
# ParamsList = []
ops = "+-"
opsdict = { "+": operator.add, "-": operator.sub }
# if len(initial_condi)!=len(VarList):
# sys.exit('error: the number of initional conditions do not equal to the number of variables')
def odeFunc(Y, t, model, K):
return GenModel(Y, model, K)
def GenModel(Y, model, K):
# New array of floating-point zeros the size of Y
dydt = zeros_like(Y)
for i, derivative in enumerate(model):
for j, operator in enumerate(derivative):
# Sequentially compute dy/dt for each variable in Y
dydt[i] = opsdict[operator](dydt[i],K[j]*Y[j])
return dydt
# Returns a nicer-looking string for a derivative expression given the encoding
def derivString(vars, deriv):
result = ""
for i, v in enumerate(vars):
if i == 0 and deriv[i] == '+':
result += v
else:
result += deriv[i]+v
return result
# main
numvars = int(input("Enter number of variables\n> "))
VarList = ascii_lowercase[:numvars]
nummodels = (2**numvars)**numvars
# begin looping
input_ = ""
while input_ != "quit":
print("\n%d possible models" % nummodels)
input_ = input("Enter model ID (zero-indexed) or 'quit'\n> ")
# Basic input filtering
if input_ == "quit":
continue
elif not input_.isdigit():
print("Input must be a non-negative integer")
continue
ID = int(input_)
if ID >= nummodels or ID < 0:
print("Invalid ID")
continue
# itertools.product creates a generator for all possible combinations of +-
derivatives = product(ops, repeat=numvars)
# We take the product again to generate all models
models = product(derivatives, repeat=numvars)
# islice takes the specified model
model = next(islice(models, ID, None))
# Display dy/dt for each variable
print("Model %d:" % ID)
IDtitle = []
for i, variable in enumerate(VarList):
tempstring = "d%c/dt = %s" % (variable, derivString(VarList, model[i]))
IDtitle.append(tempstring)
print("\t" + tempstring)
# User specifies the initial values of all variables.
# This process can be automated but this is to demonstrate that the progam
# accepts any input
init_cons = []
params = []
confirm = ""
while confirm not in ("y", "n"):
confirm = input("Run this model? (y/n)\n> ")
if confirm == "n":
continue
print("\nEnter <initial value, parameter> pairs separated by ','")
for i, variable in enumerate(VarList):
iv_param = list(map(float, input("> %c: " % variable).split(',')))
init_cons.append(iv_param[0])
params.append(iv_param[1])
print("\nRunning ODEint...", end='')
result = odeint(odeFunc, init_cons, t_range, args=(model,params))
print(" done.")
print("Plotting results...", end='')
f = figure(ID)
title(", ".join(IDtitle))
for i, variable in enumerate(VarList):
plot(t_range, result[:,i], label=variable)
legend()
axhline(0, color='k')
savefig("model"+str(ID))
close(f)
print("done.")
print(" -- Bye --")
I am working on a assignment and am encountering this error. NameError: name 'recPower' is not defined
Write a recursive function called pow(base, power) that takes in two numbers. First number is a base and the second number is a power. The function will return the number raised to the power. Thus, if the number is 2 and the power is 4, the function will return 16. (75 points).
Write a main() function that asks for a number and a power. Then calls the recursive function created in step 1 (15 points).
DO NOT use the algorithm on page 432 of your book:
def: recPower (a, n):
if n == 0:
return 1
else:
factor = recPower (a, n//2)
if n%2 == 0:
return factor * factor
else:
return factor * factor * a
My current code is as follows
def main():
a=input("enter base :")
n=input("enter power :")
print ("Total = ",recPower(a,n))
main()
def recPower (a,n):
if n == 0:
return 1
else:
return a*recPower(a,n-1)
`
The error I get when I run it is :
Traceback (most recent call last):
File ".py", line 7, in
main()
File ".py", line 5, in main
print ("Total = ",recPower(a,n))
NameError: name 'recPower' is not defined
Functions are stored in identifiers. You have to define it first. Try this one:
def recPower(a, n):
if n == 0:
return 1
else:
return a * recPower(a, n - 1)
def main():
a = int(input("enter base :"))
n = int(input("enter power :"))
print ("Total = ", recPower(a, n))
main()
Define your 'run' function after 'recPower'.
As also mentioned you need to convert the strings that are returned from input() into integers or floats, using either int() or float(). When you try to operations like division you'll get TypeError exceptions.
write your method above the main code, because if you write at under the main code method is undefinied
functions must be defined before any are used.
try this code
def recPower(a, n):
# or just a, n = int(a), int(n) is fine
if isinstance(a, str):
a = int(a)
if isinstance(n, str):
n = int(n)
if n == 0:
return 1
else:
return a * recPower(a, n - 1)
def main():
a = input("enter base :")
n = input("enter power :")
print ("Total = ", recPower(a, n))
main()