Python pyttsx3语音播报循环退出判断逻辑异常问题
pyttsx3语音播报程序循环异常退出问题修复
故障复现代码
import pyttsx3 robot = pyttsx3.init() while True: robot.say(input('Write something that you need me to say:\n')) robot.runAndWait() n = (input('if you need to quit type : quit , if you need to write again press any button\n')) if n == 'Quit' or 'quit' or 'QUIT': break else: continue
故障原因
核心问题出在条件判断语句的写法错误:
原判断逻辑if n == 'Quit' or 'quit' or 'QUIT':不符合Python语法规则,or运算符会对每一段独立表达式做真值校验,上述写法实际执行的判断是:(n == 'Quit') 为真,或者 'quit' 这个字符串本身为真,或者 'QUIT' 这个字符串本身为真。Python中非空字符串的布尔值恒为True,因此这个判断条件永远成立,无论用户输入什么内容都会触发break直接退出循环。
修复方法
修正条件判断逻辑即可,推荐直接将用户输入统一转为小写后和quit做匹配,不需要单独枚举所有大小写组合,代码更简洁易维护:
import pyttsx3 robot = pyttsx3.init() while True: input_content = input('Write something that you need me to say:\n') robot.say(input_content) robot.runAndWait() operation = input('if you need to quit type : quit , if you need to write again press any button\n') if operation.lower() == 'quit': break
修复后逻辑符合预期:输入任意大小写形式的quit都会退出程序,输入其他任意内容都会自动回到循环开头,重新等待用户输入要播报的内容。
内容的提问来源于stack exchange,提问作者Eyad
相关产品推荐
相关产品推荐

