Python编程无意循环

问题描述:

counter=0 
initials=0 
name1=raw_input("Please enter your first name!") 
name2=raw_input("Please enter your middle name!") 
name3=raw_input("Please enter your last name!") 
option=str(raw_input("a)Print the length of my name\nb)Print\nc)Exit\nChoose one of the options.")) 
while option != "c" or option != "C": 
    if (option=="a" or option=="A"): 
     print "Your first name has " + str(len(name1)) + " letters." 
     print "Your second name has " + str(len(name2)) + " letters." 
     print "Your last name has " + str(len(name3)) + " letters." 
    elif (option=="b" or option=="B"): 
     print name1[0] + "." + name2[0] + "." + name3[0] 
    elif (option=="c" or option=="C"): 
     break 

这是我的代码。由于某种原因,它会一直进入无限循环。一旦用户选择他们的选项,我该如何停止它?我只需要在那里输入用户选择一次的选项。Python编程无意循环

+2

您的代码的缩进似乎关闭。请检查。 – usr2564301

您需要在while循环的结尾添加行

option=str(raw_input("a)Print the length of my name\nb)Print\nc)Exit\nChoose one of the options.")) 

。这将再次要求用户输入,如果它是cC,它将退出。

您还应该更改您的while条件。使用or将导致它始终为False。您可能应该使用while True(因为c输入在循环内进行检查)。

希望这会帮助你,只需要改变你的条件到True并改变你的期权声明的位置。

counter=0 
initials=0 
name1=raw_input("Please enter your first name!") 
name2=raw_input("Please enter your middle name!") 
name3=raw_input("Please enter your last name!") 

while True: 
    option=str(raw_input("a)Print the length of my name\nb)Print\nc)Exit\nChoose one of the options.")) 
    if (option=="a" or option=="A"): 
     print "Your first name has " + str(len(name1)) + " letters." 
     print "Your second name has " + str(len(name2)) + " letters." 
     print "Your last name has " + str(len(name3)) + " letters." 
    elif (option=="b" or option=="B"): 
     print name1[0] + "." + name2[0] + "." + name3[0] 
    elif (option=="c" or option=="C"): 
     break 
+0

为了避免输入'option ==“c”“或选项==”C“'或类似的输入,可以将变量'option'设置为'option = str(raw_input(”x“))。 ()'在这[主要](https://gist.github.com/rrrub/ee4257a737c3e8f8ca42b8c9bfa5a97b) – rrrub

+0

@gist - rrrub是你是对的,我们也可以这样做... 'option = str(raw_input (“a)打印我的名字长度\ nb)打印\ nc)退出\ n选择其中一个选项。”))。lower()' 之后我们不必添加'或' '信(选项== “C”') –