在输入中输入两个条件

时间:2018-08-08 19:02:32

标签: python python-3.x

如果我运行此程序

emails=[]
a=(0)
while a==(0):
    user_email= input("Please write email")
    if "@" in user_email:
        if ".edu"in user_email:
            print("Adding email to list")
            emails.append(user_email)
            print(emails)
        else:
            a=(0)
       a=(0)
   else:
    print("Error:Email does not meet requirements")
       a=(0)

我键入的输入仅满足其中一项要求,它仅在一种情况下显示错误消息。由于无法在“ if”语句中写两个条件,因此无法满足要求的两种情况下如何显示错误消息。

3 个答案:

答案 0 :(得分:1)

使用and关键字,为所有其他情况打印错误消息。

if '@' in user_email and '.edu' in user_email:
    pass
else:
    print('error')

if all(keyword in user_email for keyword in ['@', '.edu']):
    pass
else:
    print('error')

答案 1 :(得分:1)

emails=[]
while True:
    user_email= input("Please write email: ")
    if user_email.count("@") == 1 and user_email.count(".edu") == 1:
            print("Adding email to list")
            emails.append(user_email)
            print(emails)
    else:
        print("Error:Email does not meet requirements")

或使用正则表达式:

import re
emails=[]
while True:
    user_email= input("Please write email: ")
    email_pt = re.compile("^[\w.]+@[\w.]+\.edu$")
    if email_pt.search(user_email):
        print("Adding email to list")
        emails.append(user_email)
        print(emails)
    else:
        print("Error:Email does not meet requirements")

答案 2 :(得分:0)

这是一个供您使用的简单函数,可以代替嵌套的if语句:

#A nice function that returns true if @ and .edu are in the mail
def matches(user_email):

    boolean = True

    if '@' not in user_email:
        boolean = False

    if '.edu' not in user_email:
        boolean = False

    return boolean


#Your new code
emails=[]
a=(0)
while a==(0):
    user_email= str(input("Please write email: "))

    #New function in use
    if matches(user_email):
        print("Adding email to list")
        emails.append(user_email)
        print(emails)
    else:
        print("Error:Email does not meet requirements")

希望这会有所帮助! :D