Python中get_int()函数陷入无限循环的原因及解决咨询
关于Python中get_int()函数的输入验证问题
我最近开始学习Python,特意将get_int()和get_float()的定义写得不同,想了解在main()中接收输入并传递给函数调用的效果。以下是我的代码:
#!/usr/bin/env python3 def get_int(prompt, low, high): while True: #number = float(input(prompt)) if prompt <= low or prompt > high: print("Entry should be greater than ", low, "and less than or equal to ", high) else: return prompt def get_float(prompt, low, high): while True: number = float(input(prompt)) if number <= low or number > high: print("Entry should be greater than ", low, "and less than or equal to ", high) else: return number def calculate_future_value(monthly_investment, yearly_interest, years): # convert yearly values to monthly values monthly_interest_rate = yearly_interest / 12 / 100 months = years * 12 # calculate future value future_value = 0.0 for i in range(months): future_value += monthly_investment monthly_interest = future_value * monthly_interest_rate future_value += monthly_interest return future_value def main(): years = 0 monthly_investment = 0.0 yearly_interest_rate = 0.0 choice = "y" while choice.lower() == "y": # get input from the user monthly_investment = get_float("Enter monthly investment: ", 0, 1000) yearly_interest_rate = get_float("Enter yearly interest rate: ", 0, 15) years = int(input("Enter number of years: ")) years = get_int(years, 0, 15) # get and display future value future_value = calculate_future_value( monthly_investment, yearly_interest_rate, years) print(f"Future value: {round(future_value, 2)}") print() # see if the user wants to continue choice = input("Continue? (y/n): ") print() print("Bye!") if __name__ == "__main__": main()
我仅在get_int()函数遇到问题:当传入low=0、high=15时,若输入年份为0或16,会无限打印if子句中的提示;输入范围内值则正常。我不确定能否直接在函数定义中使用函数参数而不赋值给局部变量,若允许的话,是get_int()内的while循环有误,还是需要在main()的输入处添加while循环?
问题分析与解决
你的get_int()函数逻辑存在核心错误:
- 函数参数里的
prompt被你当成了要验证的输入值,但实际上这个参数应该是提示文本,就像get_float()里的用法一样。你现在把main()中已经输入的years值传给了get_int的prompt参数,然后在循环里反复判断这个固定值,一旦不符合条件就无限循环,因为没有重新获取新输入的逻辑。 - 直接用函数参数作为验证值本身没问题,但前提是这个参数是动态变化的,而你这里的参数是固定的,所以循环无法终止。
修正后的get_int()函数
把get_int()改成和get_float()类似的逻辑,让函数内部负责获取输入并验证:
def get_int(prompt, low, high): while True: try: number = int(input(prompt)) if number <= low or number > high: print(f"Entry should be greater than {low} and less than or equal to {high}") else: return number except ValueError: print("Please enter a valid integer.")
修正main()中的调用方式
不需要提前用int(input())获取值,直接调用get_int()即可:
# 替换原来的两行 years = get_int("Enter number of years: ", 0, 15)
这样修改后,get_int()会像get_float()一样,持续提示用户输入直到符合要求,不会出现无限循环的问题。另外添加了try-except块处理非整数输入的情况,让函数更健壮。
内容的提问来源于stack exchange,提问作者Learner
相关产品推荐
相关产品推荐

