You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3简易书店程序报错求助:NameError变量未定义问题排查

解决你的Python书店程序NameError问题

Hey there! Let's fix that frustrating NameError you're seeing in your bookstore program.

错误原因分析

The NameError: name 'book_choice' is not defined error means exactly what it says: you tried to use the variable book_choice (and probably book_price too) when calling your book_store function, but you never created or assigned a value to those variables first. Python has no idea what book_choice refers to because you didn't tell it!

修复后的完整代码

Here's a working version of your program that includes user input and fixes the variable definition issue:

# 定义处理订单的函数
def book_store(book, price):
    # 返回格式化后的订单信息
    return f"order: '{book}' costs '{price} dollar'"

# 从用户输入获取书籍名称和价格,定义所需变量
book_choice = input("Enter the name of the book you want: ")
book_price = input("Enter the price of the book: ")

# 调用函数并打印结果
print(book_store(book_choice, book_price))

关键修复点

  • We added input() calls to collect user input and assign those values to book_choice and book_price. Now Python recognizes these variables when we pass them to the book_store function.
  • The function itself uses an f-string to format the output exactly as you wanted—clean and readable.

额外优化建议

If you want to make the price display more polished (like handling numbers properly instead of strings), you can convert the price input to a float:

book_price = float(input("Enter the price of the book: "))
# 调整函数里的字符串格式,让价格显示更自然
def book_store(book, price):
    return f"order: '{book}' costs ${price:.2f}"

This will show the price as a currency value (e.g., $19.99 instead of '19.99 dollar').

内容的提问来源于stack exchange,提问作者user9126689

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:03:34