2017-10-14 56 views
0

我试图实现自定义验证......我的目标是,如果用户的回复不是“Y”,或不是“N”,或不是“Q”,他们循环回到顶部。否则打破。
在Python中自定义验证

我试过的两个选项都会继续循环,即使给出了正确的响应。

这是我已经试过: 选项1:

""" Use custom validation. """ 
while True: 
    n_put = input('Would you like to perform a new Google image search?' + user_options()) 
    if n_put is not "Y" or not "N" or not "Q": 
     print('Invalid response. Please read the prompt carefully. ') 
    else: 
     break 

选项2:

""" Use custom validation. """ 
while True: 
    n_put = input('Would you like to perform a new Google image search?' + user_options()) 
    if n_put is not any(["Y", "N", "Q"]): 
     print('Invalid response. Please read the prompt carefully. ') 
    else: 
     break 
+2

'如果不是n_put in ['Y','N','Q']:'或'如果不是n_put =='Y'而不是n_put =='N'' ... – cwallenpoole

+0

可能重复[请求用户输入,直到他们给出有效的响应为止(https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – wwii

+0

@wwii ,我的问题涉及多个非条件。没有太多的循环。 –

回答

0

正确选项1:

while True: 
    n_put = input('Would you like to perform a new Google image search?' + user_options()) 
    if not (n_put == "Y" or n_put == "N" or n_put == "Q"): 
     print('Invalid response. Please read the prompt carefully. ') 
    else: 
     break 

,正确选项2:

while True: 
    n_put = input('Would you like to perform a new Google image search?' + user_options()) 
    if n_put not in ["Y", "N", "Q"]: 
     print('Invalid response. Please read the prompt carefully. ') 
    else: 
     break