为何我的幂运算代码运行无反应且不提示输入?
问题分析与修复方案
核心问题
你只定义了raise_to_power函数,但从来没有调用这个函数,所以运行代码时,函数内部的逻辑完全没被执行,自然不会出现输入提示,程序看起来毫无动作。
额外问题
除了函数未调用,你的代码还有两个明显问题:
- 函数定义了
base_num和pow_num参数,但内部又用input重新赋值,等于参数完全没用,纯属多余。 - 如果你输入的
pow_num是浮点数(比如2.5),while i <= pow_num会陷入死循环——因为i是整数递增,永远到不了2.5,程序会一直跑下去。
修复后的代码
情况1:仅支持正整数次幂
def raise_to_power(): result = 1 i = 1 base_num = float(input("Your base number= ")) # 限制输入为整数,避免死循环 pow_num = int(input("Your Power number = ")) if pow_num == 0: print(result) else: while i <= pow_num: result = result * base_num i += 1 print(result) # 必须调用函数才会执行内部逻辑 raise_to_power()
情况2:支持浮点数次幂(借助math模块)
如果需要计算非整数次幂,直接用Python内置的math.pow更靠谱,自己写循环实现不了:
import math def raise_to_power(): base_num = float(input("Your base number= ")) pow_num = float(input("Your Power number = ")) result = math.pow(base_num, pow_num) print(result) raise_to_power()
内容的提问来源于stack exchange,提问作者Gürhan Özdemir
相关产品推荐
相关产品推荐

