我如何继续重复“如果”?

时间:2014-12-22 20:48:50

标签: python if-statement

我希望我的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.")

5 个答案:

答案 0 :(得分: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...

答案 1 :(得分: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

答案 2 :(得分: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"

答案 3 :(得分:0)

while selection1 != "Q":
    if selection1 == "C": 
        print "Ok"
    elif selection1 == "E": 
        print "Ok"
    else:  
        print " Chose again"
print "quit"
quit()

答案 4 :(得分: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()

但您已经从之前的帖子中得到了答案。这只是另一种选择。