如何解决基本功能中简单的python代码中的错误,这些错误会为接收到的数字供电
我正在学习python,这是一个基本代码,我不知道为什么它不起作用。对于变量“索引” ,我遇到了错误“未使用的变量'索引'”。并在命令时出现错误“无法访问的代码”。
def power(base,pow):
result = 1
for index in range(pow):
result *= base
return result
while input("would you like to continue? ") == "yes":
print(power(input("enter the base: \n"),input("enter the power: \n")))
解决方法
您的代码没有错误。您得到的是编译器警告,而不是错误。目前,您的代码中的while循环将永远不会执行。只需在函数声明之外使用while循环即可摆脱警告。
def power(base,pow):
result = 1
for index in range(pow):
result *= base
return result
while input("would you like to continue? ") == "yes":
print(power(input("enter the base: \n"),input("enter the power: \n")))
,
正如@Mark Jacobson所提到的,这些是IDE警告。您的代码仍将运行。
def power(base,pow):
result = 1
for index in range(pow): # you set index to a value,but never use it
result *= base
return result # your function will exit here,so the code below will never run
while input("would you like to continue? ") == "yes":
print(power(input("enter the base: \n"),input("enter the power: \n")))
就像@Aniket在另一个答案中提到的那样,如果不需要或无需缩进就可以删除while循环,因此它不在函数中。
警告并没有损害程序,但是,如果要删除警告,请使用pow
进行迭代。
def power(base,pow):
result = 1
while pow > 0:
result *= base
pow -= 1
return result
,
您的代码需要稍作修改:
def power(base,pow):
result = 1
for index in range(pow):
result *= base
return result
while input("would you like to continue? ") == "yes":
print(power(int(input("enter the base: \n")),int(input("enter the power: \n"))))
,
def power(base,pow):
result = 1
for index in range(pow):
result *= base
return result
while (input("would you like to continue? ") == "yes"):
print(power(int(input("enter the base: \n")),int(input("enter the power: \n"))))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。