Python自动选片程序条件分支异常:始终执行if而非elif
问题分析与修复:自动选片程序分支逻辑错误
你的程序始终执行if分支的核心原因是条件判断语法完全错误,具体问题和修复方案如下:
错误点拆解
- 误用赋值运算符
:=:
你写的if answer := 'Movie''movie'是赋值操作而非比较判断。这行代码会把拼接后的字符串'Moviemovie'赋值给answer,而赋值表达式的返回值是这个非空字符串,在布尔判断里永远为True,导致第一个if分支必然触发,elif分支完全没机会执行。 - 字符串拼接逻辑错误:
Python中相邻字符串会自动拼接,'Movie''movie'会变成'Moviemovie',这完全不是你想要的“匹配任意电影相关输入”的逻辑。
修正后的代码
answer = input('Welcome to Showpicker. First off, would you like to watch a movie or a TV show? ') # 用in判断输入是否在目标选项列表中 if answer in ['Movie', 'movie']: import time import random print('Great choice!') time.sleep(1) print('I will now pick a movie for you to watch!') movie = ['The Hunt','Atonement','Da Vinci Code','The Menu','Dead Poets Society','Harry Potter Series','The Shining','Exorcist','1917','Maurice','Call Me by Your Name','The Father','Fantastic Beasts Series','James Bond Series','Dune','Dune 2','Indiana Jones Series','Drive','Blade Runner Series','John Wick Series','Mission Impossible series','Drive','The Name of the Rose'] time.sleep(3) print(random.choice(movie)) time.sleep(3) print("Enjoy!Don't forget your popcorn.") exit() elif answer in ['TV show', 'TVshow', 'tv show', 'tvshow']: import time import random print('Great choice!') time.sleep(1) print('I will now pick a TV show for you to watch!') TV = ['Hannibal','Peaky Blinders','House MD','Stranger Things','Breaking Bad','The Mentalist'] time.sleep(3) print(random.choice(TV)) time.sleep(1) print("Enjoy!Don't forget your popcorn.") exit()
额外优化建议
- 可以把输入转为小写后判断,简化选项列表:
if answer.lower() in ['movie', 'tv show', 'tvshow'],这样能兼容更多输入格式(比如MOVIE)。 - 建议把
import time和import random放在代码开头,避免在分支内重复导入模块。
内容的提问来源于stack exchange,提问作者Silverfish
相关产品推荐
相关产品推荐

