Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用循环计算提升到幂的值_Python - Fatal编程技术网

Python 使用循环计算提升到幂的值

Python 使用循环计算提升到幂的值,python,Python,在课堂上,我们正在制作一个使用循环的程序,通过循环将数字提升到幂。我必须走到这一步,但我迷路了。正在寻求帮助 base=int(raw_input("What number do you want to be the base")) exp=int(raw_input("What do you want to be the power")) def power(base, exp): res=1 for _ in range(exp): number=res*b

在课堂上,我们正在制作一个使用循环的程序,通过循环将数字提升到幂。我必须走到这一步,但我迷路了。正在寻求帮助

base=int(raw_input("What number do you want to be the base"))
exp=int(raw_input("What do you want to be the power"))

def power(base, exp):
    res=1
    for _ in range(exp):
        number=res*base
    return number
    print number

您正在覆盖每个循环中number的值,因此最终结果是它永远不会更改。相反,你应该这样做

base=int(raw_input("What number do you want to be the base"))
exp=int(raw_input("What do you want to be the power"))

def power(base, exp):
    res=1
    for _ in range(exp):
        res = res*base
    print res
    return res

print power(base, exp)
注意,我将
print
语句放在return语句之前;否则它就不会被执行了。最后,在末尾有一个额外的print语句来调用函数。事实上,使用这个print语句,您甚至不再需要
power()
方法中的print,因此您也可以删除它

如果希望在没有for循环的情况下执行此操作,可以使用

def power(base, exp):
    return base**exp
  • 您从未调用您定义的函数
    power
    。请在最后尝试
    打印电源(基本,exp)
  • 如果要调用它,它将循环一些,然后返回
    number
    ,即
    res*base
    ,即
    1*base
    (因为您从不更改任何内容,每次都在循环中进行相同的计算)。考虑<代码> RES=RESbase<代码>(或等效地,<代码> RES*= BASE< /代码>),并返回<代码> RES <代码>,而不是<代码>编号<代码>
  • 您也不会打印任何内容,因为它超出了
    return
    语句的范围

如果您的问题已得到解决,请不要忘记以下内容:)