简体   繁体   中英

simple bookstore program on python3

I'm learning Python and I'm trying to write a simple bookstore program using functions and user input. It takes parameters (book, price) and prints "order: ' your book choice' costs 'x dollar' " but I can't get it to work. Could you check out my code and help me out?

def book_store(book,price):
    book_choice = input("Enter books title: ")
    book_price = input ("Enter books price: ")

    return "Title: " + book_choice + ", costs " + book_price

print (book_store(book_choice, book_price))

NameError Traceback (most recent call last) in () 10 11 ---> 12 print (book_store(book_choice, book_price))

NameError: name 'book_choice' is not defined

You are passing two parameters that are unused, and not initialising them anyway. They are superfluous. The following works:

def book_store():
    book_choice = input("Enter books title: ")
    book_price = input ("Enter books price: ")

    return "Title: " + book_choice + ", costs " + book_price


print (book_store())

Gives:

Enter books title: Good Python
Enter books price: 2.30
Title: Good Python, costs 2.30

You're getting the error that book_choice is undefined. This is because you define book_choice inside the function and not outside of it. The way you have it now, your function should take zero arguments. But if you want to pass it the arguments of book_choice and book_price, you must define those variable outside the function.

Your code is redundant right now, it can either be:

def book_store():

    book_choice = input("Enter books title: ")
    book_price = input("Enter books price: ")

    return "Title: " + book_choice + ", costs " + book_price

print(book_store())

OR:

def book_store(book, price):

    return "Title: " + book + ", costs " + price


book_choice = input("Enter books title: ")
book_price = input("Enter books price: ")

print (book_store(book_choice, book_price))

Both versions work.

Also make sure you are using python 3, otherwise input does not return a string.

def book_store(book,price):


        book_choice = input("Enter books title: ")
        book_price = input ("Enter books price: ")

        return "Title: " + book_choice + ", costs " + book_price


print (book_store(book_choice, book_price))

book_choice and book_price are expected to to be something here, maybe , variables which have not been defined. You are passing these variables in the function book_store. This was about the error, while its not clear what you want to achieve.

Maybe you can simply. use this print.

print(book_store())

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