在python中重复一会儿条件

时间:2018-07-19 09:55:13

标签: python loops if-statement while-loop conditional-statements

我正在创建一个登录页面,其中必须涵盖所有登录测试方案。我正在验证用户输入的所有类型的输入,但是问题是,当while条件处理一个测试条件时,同一个while条件在另一个while条件运行时不会重复。如果在用户将相同的输入值放在另一种输入值之后再次出现相同的测试条件。这是我的代码:

import re
userDetails=[]
accountDetails= {"FirstName": "Ajay", "LastName": "Kumar","DateOfBirth":"24-07-1992","Account Number":"4242342345234","Balance Currency":"Rs","Balance Amount":"5000"}
specialCharacters = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
firstName=str(input("Enter First Name"))

while True:
    if firstName=="":
        print("Name cannot be blank")
        firstName=str(input("Enter First Name"))

while True:
    if firstName.isdigit():
        print("Name cannot be in digits")
        firstName=str(input("Enter First Name"))

while True:
    if specialCharacters.search(firstName) != None:
        print("Please don't enter special characters")
        firstName=str(input("Enter First Name"))

while True:
    if firstName!=accountDetails.get("FirstName"):
        print("The account does not exist with the given details, please try again")
        print("Enter valid first name")
        firstName=str(input("Enter First Name"))

else:
    userDetails.append(firstName)

4 个答案:

答案 0 :(得分:1)

使用异常和函数并一次执行所有验证:

class ValidationError(Exception):
    pass

def validate_name(name):
    name = name.strip()

    if not name:
        raise ValidationError("Name cannot be blank")

    if name.isdigit():
        raise ValidationErrir("Name cannot be in digits")

    if specialCharacters.search(name) is not None:
        raise ValidationError("Please don't enter special characters")

    if name != accountDetails.get("FirstName"):
        raise ValidationError("The account does not exist with the given details, please try again")


def get_first_name():
    while True:
        first_name = input("Enter First Name")
        try:
            validate_name(firstName)
        except ValidationError as e:
            print(str(e))
        else:
            # ok we're good
            return first_name

first_name = get_first_name()
do_something_with(first_name)  

答案 1 :(得分:0)

一种编写方式:

import re

specialCharacters = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
accountDetails= {"FirstName": "Ajay", "LastName": "Kumar","DateOfBirth":"24-07-1992","Account Number":"4242342345234","Balance Currency":"Rs","Balance Amount":"5000"}

not_valid = True
while not_valid:
    firstName=str(input("Enter First Name: "))
    if firstName == "" or specialCharacters.search(firstName) != None or firstName.isdigit() or firstName!=accountDetails.get("FirstName"):
        not_valid = True
        continue

    else:
        not_valid = False

也可以休息一下。

答案 2 :(得分:0)

我建议将验证重构为一个单独的函数,诸如此类。

import re

userDetails = []

accountDetails = {
  "FirstName": "Ajay",
  "LastName": "Kumar",
  "DateOfBirth": "24-07-1992",
  "Account Number": "4242342345234",
  "Balance Currency":"Rs",
  "Balance Amount":"5000",
}

specialCharacters = re.compile('[@_!#$%^&*()<>?/\|}{~:]')

def validate(accountDetails, firstName):
    if not firstName:
        return "Name cannot be blank"

    if firstName.isdigit():
        return "Name cannot be in digits"

    if specialCharacters.search(firstName):
        return "Please don't enter special characters"

    if firstName != accountDetails.get("FirstName"):
        return "The account does not exist with the given details, please try again"

    return None  # No error

while True:
    firstName = str(input("Enter First Name"))
    error = validate(accountDetails, firstName)
    if error:
        print(error)
    else:
        break

userDetails.append(firstName)

答案 3 :(得分:0)

您需要了解while的工作原理,或者通常是循环。让我们看一下您的代码-

firstName=str(input("Enter First Name"))
# We got an input
while True: # (Oh, I have to run indefinitely)
    ....

第一个while True将使您陷入无限循环,并且此后将不再执行代码。与其执行此操作,不如执行以下操作-

while not len(firstName): # (Okay, I will run till I get a non empty firstname)
    # your code
# and subsequent conditions 
while not firstName.isdigit():
    # your code

#.... and so on

或者更好的是,将这些condition放入function