为何添加自定义函数后while循环无法持续运行?
问题分析与修复
你的代码里while循环无法正常运行,核心问题有两个:
- 输入
text和shift的代码写在循环外面,只会执行一次,循环里没法更新用户输入 - while循环逻辑错误:当
text != 'q'时直接continue,导致程序陷入无限空循环,既不处理新输入也不退出;就算输入q,也没有退出循环的逻辑
修正后的代码
# 字母列表,重复一次避免索引越界 alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] * 2 def encode(plain_text, shift_amount): cipher_text = '' for letter in plain_text: # 只处理字母,非字母直接保留 if letter in alphabet: position = alphabet.index(letter) # 取模处理shift超过26的情况 new_position = position + (shift_amount % 26) new_letter = alphabet[new_position] cipher_text += new_letter else: cipher_text += letter print(f'加密后的字符串是: {cipher_text}') while True: text = input("输入你的消息(输入q退出):\n") # 输入q直接退出循环 if text == 'q': break # 处理shift输入可能不是数字的情况,避免报错 try: shift = int(input("输入偏移量:\n")) encode(plain_text=text, shift_amount=shift) except ValueError: print("请输入有效的数字作为偏移量!")
关键修改点
- 将输入
text和shift的逻辑移到while循环内部,每次循环都能获取新的用户输入 - 增加
text == 'q'时的break语句,触发循环退出 - 给encode函数添加非字母字符的处理,避免输入空格、数字时报错
- 对shift值取模,就算输入超过26的数字也能正常加密
- 增加try-except捕获偏移量输入非数字的情况,提升程序健壮性
内容的提问来源于stack exchange,提问作者HunterDebugg
相关产品推荐
相关产品推荐

