猿问

虽然循环仍在循环

我需要将“F”或“M”作为用户的输入。所以有我的代码:


a = input("")

while a != 'F' or a != 'M':

    a = input("")

但即使用户输入“M”或“F”或其他任何内容,它仍会循环。所以我试过这个:


genre = input("")

while genre != 'F':

    genre = input("")

它有效..我只需要'M'或'F',有人可以帮我吗?


白衣非少年
浏览 193回答 2
2回答

月关宝盒

你需要and而不是orwhile a != 'F' and a != 'M'因为a不能一次等于两件事。就像现在一样, if a=='M', then a != 'F',所以循环继续(反向值相同)。所以,循环永远不会结束。

呼啦一阵风

a != 'F' or a != 'M'永远是其中之一 True。尝试这个:while a not in 'FM':    ...虽然这也会接受FM;更好的方法是使用:while a not in set('FM'):    ...
随时随地看视频慕课网APP

相关分类

Python
我要回答