技术求助:编写无需for/while循环的数字输入求和程序
不用循环实现数字输入求和的方案
你需要实现读取用户输入数字并返回总和的功能,且不能使用for或while循环,这里可以用递归来替代循环——递归通过函数自身调用自身的方式,能达到循环的效果但无需显式循环语句。
先看你现有的while循环实现代码:
n = 0 count = 0 # `enter code here` user = input('Enter Numbers:\n> ') while user != 'done': try: n = n + float(user) except: print('Enter Numbers or "done"') user = input('> ') count = count + 1 if user == 'done': print('Total:',n) # this works for me but i need to do it without using loops like 'for' or 'while' :(
递归实现版本
以下是不使用循环的递归实现,逻辑和你的原代码一致,同时处理了输入异常:
def get_total(): user_input = input('> ') # 输入done时终止递归,返回0作为累加的基础值 if user_input == 'done': return 0.0 try: # 转换为数字后,递归调用自身并累加结果 num = float(user_input) return num + get_total() except ValueError: # 输入非数字时提示错误,继续递归 print('请输入数字或"done"') return get_total() print('Enter Numbers:') total = get_total() print('Total:', total)
扩展:同时统计输入数量
如果需要保留原代码中count的统计功能,也可以让递归函数同时返回总和与计数:
def get_total_and_count(): user_input = input('> ') if user_input == 'done': return 0.0, 0 try: num = float(user_input) # 递归获取后续的总和与计数,再累加当前值和计数 total, count = get_total_and_count() return num + total, count + 1 except ValueError: print('请输入数字或"done"') return get_total_and_count() print('Enter Numbers:') total, count = get_total_and_count() print('Total:', total) print('Count:', count)
内容的提问来源于stack exchange,提问作者German Fmz
相关产品推荐
相关产品推荐

