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.
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.