Python编程无意无限循环

时间:2016-11-27 18:44:16

标签: 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

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

2 个答案:

答案 0 :(得分:5)

您需要添加

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

在while循环结束时。这将再次询问用户输入,如果是cC,则会退出。

您还应该更改while条件。使用or会使其始终为False。您应该使用while True代替(在循环内检查c输入。)

答案 1 :(得分:4)

希望这会对您有所帮助,只需将您的状态改为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