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

Python中如何正确引用输入变量?代码运行崩溃求助

问题原因及解决方法

你的代码崩溃是因为第二行的input()函数调用错误——input()只能接收一个字符串类型的提示参数,但你把CLASS作为第二个参数传进去了,导致参数数量不匹配的TypeError。

要在输入提示里引用已有的变量,需要把变量值嵌入到提示字符串中,以下是几种正确写法:

推荐写法(Python 3.6+):f-string格式化

f-string是最简洁直观的方式,直接在字符串前加f,然后用{变量名}嵌入变量:

CLASS = str(input("What is the name of your class: "))
HOURS = int(input(f"How many hours a week do you spend in {CLASS}? "))

字符串拼接

用+把多个字符串和变量拼接成一个完整的提示字符串:

CLASS = str(input("What is the name of your class: "))
HOURS = int(input("How many hours a week do you spend in " + CLASS + "? "))

str.format()方法

用{}作为占位符,通过format()方法传入变量值:

CLASS = str(input("What is the name of your class: "))
HOURS = int(input("How many hours a week do you spend in {}? ".format(CLASS)))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 11:28:06