如何使输入拒绝负值并专门打印负值时的语句



目前,当我输入负值时,它将打印"输入数据不是正确的格式 - 重试"。但是,我希望它打印语句"该值不能为负数"。我尝试将其添加为附加条件,但它不起作用。关于尝试什么有什么建议吗?

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")
继续评论

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")

输出

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

如果您的字符串包含数字以外的任何内容,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.")

最新更新