我正在尝试测试每个输入然后返回该数字被清除然后进行数学计算。例如,用户输入N而不是我希望它输出的数字不是数字,而如果用户输入1,那么我希望它移动到下一个要求功率的功能,然后做同样的事情,如果通过然后转到输出问题答案的最后一节。
程序传递非数字区域的错误,但是当它到达最后一个函数时,它告诉我基数和功率定义。
代码是用Python2和Python3编写的。一切都很好。我主要使用python3。
# Below we are creating the recursive statement to do the math for us. We are calling Base and Power
# from the main function where the user Inputs the numbers.
def pow(base, power):
if power == 0:
return 1
if power == 1:
return base
else :
return base * pow(base, power - 1)
def determineBase():
while True:
try:
base = int(input ('Please Enter A Base: '))
except ValueError:
print("Please use whole numbers only. Not text nor decimals.")
continue
else:
return base
def determinePower():
while True:
try:
power = int(input ('Please Enter A Power: '))
except ValueError:
print("Please use whole numbers only. Not text nor decimals.")
continue
else:
return power
def main():
determineBase()
determinePower()
pow(base,power)
print("The answer to",base,"to the power of", power,"is", pow(base,power),".")
main()
答案 0 :(得分:0)
def main():
determineBase()
determinePower()
pow(base,power)
此处,base
和power
均未定义。你的意思是存储那些函数调用的结果,然后传递那些:
def main():
base = determineBase()
power = determinePower()
pow(base, power)
答案 1 :(得分:0)
问题不在递归函数中,而是在主函数内部。
问题是由于您将base
作为参数传递给pow()
函数而没有先定义变量base(power
随后也是如此) )。
换句话说,你需要的是:
def main():
base = determineBase()
power = determinePower()
pow(base,power) #this line could probably be removed
print("The answer to",base,"to the power of", power,"is", pow(base,power),".")
目前,您还没有存储这两个功能的值。