简体   繁体   中英

How add checks/validations in python for user input?

Please help regarding the below-given questions I want to solve. I am trying to create a simple book store programme and now I want to add the below mentioned checks and validations.

  1. Need to ensure that all data is entered. That is, there should be no blank entries. If any of these were not entered, do not record that entry and go straight to asking if they wish to continue.
  2. Ensure the purchase price and sell price is greater than 0. If it is not in that range, do not record that entry.
  3. Ensure that the purchase price is less than the selling price. If it is not in that range, do not record that entry.
  4. Ensure that the user only enters "y", "Y", "n", "N" if not continue to ask until they enter a valid result.
flag = True
books = []
while flag:
    title = input("Title: ")
    author = input("Author: ")
    purchase_price = float(input("Purchase_Price: "))
    sell_price = float(input("Sell_Price: "))
    margin = ((sell_price-purchase_price)/purchase_price)*100
    continues = input("Do you want to enter more books? y/n")

    book = (title,author,purchase_price,sell_price,margin)
    books.append(book)

    if continues == 'Y' or 'y':
        continue;

    elif continues == 'n' or 'N':
        print(books)
        flag = False

If you want to have it elegant, check out https://docs.python-cerberus.org/en/stable/ . So you store all the input into a dictionary and then apply the scheme that defines the rules. I didn't try that myself, but the linked documentation seems simple to follow.

Alternatively you can write own plain code to do the validation. For instance, if you expect a positive integer, you can

def convert_to_positive_int(raw_input):
    val = int(raw_input)
    if val < 1:
        raise ValueError("Positive integer input expected")
    return val

while True:
    raw_input = input("Enter positive integer:" )
    try:
        return convert_to_positive_int(raw_input)
    except ValueError as err:
        print(f"Invalid input: {str(err)}")

Being aware of above mentioned cerberus library (which I didn't know about before now), I would use it.

You can try this one

books = []
while True:
    title = input("Title: ")
    while not title:
        print('Please enter valid input!')
        title = input("Title: ")

    author = input("Author: ")
    while not author:
        print('Please enter valid input!')
        author = input("Author: ")

    sell_price = float(input("Sell_Price: "))
    while sell_price <= 0:
        print('Please enter valid input!')
        sell_price = float(input("Sell_Price: "))

    purchase_price = float(input("Purchase_Price: "))
    while (purchase_price <= 0) or (purchase_price > sell_price):
        print('Purchase price should not be greater than sell price.')
        purchase_price = float(input("Purchase_Price: "))

    margin = ((sell_price-purchase_price)/purchase_price)*100
    continues = input("Do you want to enter more books? y/n")
    while continues not in ['Y', 'y', 'n', 'N']:
        print('Please enter valid input!')
        continues = input("Do you want to enter more books? y/n")

    book = (title,author,purchase_price,sell_price,margin)
    books.append(book)

    if continues in ['n', 'N']:
        print(books)
        break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM