You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何获取For循环返回值 实现支持用户输入的指数函数

Python用户输入型指数函数运行异常问题

问题代码

我正在编写一个指数函数,开放用户输入权限后无法正常打印计算结果,初始问题代码如下:

#exponent function
      
bas_num = input("Base Number: ")
pow_num = input("Power: ")

def raise_to_power(bas_num, pow_num):
    result = 1
    for index in range(pow_num):
        result = result * bas_num
    return result

单独调用print(raise_to_power(x, y))手动传参可以正常运行,但无法适配用户输入的内容。

修复方案

核心需修正两个问题:

  • input()函数默认返回字符串类型,需要转换为整数类型才能正常参与数值运算、作为range()的合法参数
  • 增加函数调用+结果打印的语句,将用户输入的变量传入函数

修复后代码如下:

#exponent function

bas_num = int(input("Base Number: "))
pow_num = int(input("Power: "))

def raise_to_power(bas_num, pow_num):
    result = 1
    for index in range(pow_num):
        result = result * bas_num
    return result

print(raise_to_power(bas_num, pow_num))

内容的提问来源于stack exchange,提问作者Dendecko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 18:57:04