How add checks/validations in python for user input?

Question:

Please help regarding the below-given questions I want to solve. I am trying to create a simple book store program 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
Asked By: Captain

||

Answers:

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


def ask():
    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)}")

answer = ask()

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

Answered By: Dr. V

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
Answered By: Python29
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.