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
这是我的代码。由于某种原因,它一直进入无限循环。一旦用户选择他们的选项,我该如何停止?我只需要输入用户选择一次的选项。
答案 0 :(得分:5)
您需要添加
行option=str(raw_input("a)Print the length of my name\nb)Print\nc)Exit\nChoose one of the options."))
在while循环结束时。这将再次询问用户输入,如果是c
或C
,则会退出。
您还应该更改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