2014-12-22 23 views
-1

我希望我的if函数能够在python落在else之后继续重复。我怎么做?我已经添加了一个我的代码的例子。我如何不断重复“如果”?

if selection1 == "C": 
    print("Ok") 
elif selection1 == "E": 
    print("Ok") 
elif selection1 == "Q": 
    print("Ok...") quit() 
else: 
    selection1 == print("The character you entered has not been recognised, please try again.") 
+2

a while loop :) –

+0

http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/loops.html,http://www.tutorialspoint.com/python/python_loops.htm - 也有漂亮的图片 – user2864740

回答

1

我不知道你是否意味着这个但这个方案究竟是你的问题问

while True: 
    selection1 = input("Enter Character\n") 
    if selection1 == "C": 
    print("Ok") 
    elif selection1 == "E": 
    print("Ok") 
    elif selection1 == "Q": 
    print("Ok...") 
    break 
    else: 
    selection1 == print("The character you entered has not been recognised, please try again.") 

该方案需要在字符输入,并与硬编码字符检查它们。如果不匹配,它会要求用户重复,直到匹配Q字母为止。输出可以

Enter Character 
C 
Ok 
Enter Character 
E 
Ok 
Enter Character 
v 
The character you entered has not been recognised, please try again. 
Enter Character 
Q 
Ok... 
0
while True:  
    n = raw_input("\nEnter charachter: ") 
    if n == "C" OR n=="E" OR n=="Q": 
     print("Ok !") 
     break # stops the loop 
    else: 
     n = "True" 
0
while selection1 != "Q": 
    if selection1 == "C": 
     print "Ok" 
    elif selection1 == "E": 
     print "Ok" 
    else: 
     print " Chose again" 
print "quit" 
quit() 
1

这里有两种可能的方法

while True: # i.e. loop until I tell you to break 

    selection1 = GetSelectionFromSomewhere() 

    if selection1 == 'C': 
     print('Okay...') 
     break 
    elif selection1 == 'E': 
     print('Okay...') 
     break 
    elif selection1 == 'Q': 
     print('Okay...') 
     quit() 
    else: 
     Complain() 

一些较真不喜欢while True循环,因为他们不让它明确的循环条件乍一看是什么。这里的另一个上市,它具有保持break报表和其他家政你的if级联的优势,这样你就可以专注于必要的措施有:

satisfied = False 
while not satisfied: 
    selection1 = GetSelectionFromSomewhere() 
    satisfied = True 
    if selection1 == 'C': 
     print('Okay...') 
    elif selection1 == 'E': 
     print('Okay...') 
    elif selection1 == 'Q': 
     print('Okay...') 
     quit() 
    else: 
     Complain() 
     satisfied = False 
0
characters = {'C','E','Q'} 
def check(): 
    ch=raw_input("type a letter: ") 
    if ch == q: 
     quit() 
    print "ok" if ch in characters else check() 
    check() 

但是你已经在你的答案从以前的帖子。这只是一个选择。