Как сделать так, чтобы входные данные отклоняли отрицательные значения и печатали, в частности, утверждение, которое должно быть при отрицательном значении - PullRequest
0 голосов
/ 11 апреля 2019

В настоящее время, когда я ввожу отрицательное значение, будет напечатано «Входные данные не в правильном формате - попробуйте еще раз».Однако я хочу напечатать утверждение «Значение не может быть отрицательным».Я попытался добавить это как дополнительное условие, но оно не будет работать.Любые предложения о том, что попробовать?

bookTotal = 0
books = "n"
price = float(input("Enter the price for this book: "))
while books != "exit":
    books = input("Enter the number of books ordered by this customer: ")
    if books.isdigit():
        books = int(books)
        bookTotal = bookTotal + books
        income = bookTotal * price
    else:
        print("Input data not in correc format - try again")
    if books == "exit":
        print("Data entry is complete")
        print("The total number of books ordered is",bookTotal,'.')
        print("The total income generated from this book is $",income,'.')
        print("Program terminated normally")
    elif books < 0:
        print("Cannot be negative")

Ответы [ 2 ]

0 голосов
/ 11 апреля 2019

Продолжая из комментария:

bookTotal = 0
price = float(input("Enter the price for this book: "))
income = 0

while True:
    userInp = input("Enter the number of books ordered by this customer or Enter Q/q to exit: ")
    if userInp.lower() == "q":
        print("Data entry is complete")
        break
    if int(userInp) > 0:
        bookTotal = bookTotal + int(userInp)
        income = bookTotal * price
    else:
        print("Cannot be negative or 0")
print("The total number of books ordered is {}.".format(bookTotal))
print("The total income generated from these books: $ {}.".format(income))
print("Program terminated normally")

OUTPUT

Enter the price for this book: 23.50
Enter the number of books ordered by this customer or Enter Q/q to exit: -1
Cannot be negative or 0
Enter the number of books ordered by this customer or Enter Q/q to exit: 0
Cannot be negative or 0
Enter the number of books ordered by this customer or Enter Q/q to exit: 5
Enter the number of books ordered by this customer or Enter Q/q to exit: 10
Enter the number of books ordered by this customer or Enter Q/q to exit: q
Data entry is complete
The total number of books ordered is 15.
The total income generated from these books: $ 352.5.
Program terminated normally
0 голосов
/ 11 апреля 2019

isdigit() вернет False, если ваша строка содержит что-либо кроме цифр.(«-1» содержит «-», поэтому он возвращает false и вы получаете сообщение о неправильном формате.)

Я бы попробовал что-то вроде этого ...

if books.isdigit()
    # ...
elif books[1:].isdigit() and int(books[1:]) < 0:
    # ...
elif books == "exit":
    # ...
else:
    print("Input data not in correct format.")

...