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
相关产品推荐
相关产品推荐

