2016-11-27 66 views
-1
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

回答

5

您需要在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輸入在循環內進行檢查)。

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 
+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」') –