【发布时间】:2023-03-13 19:55:02
【问题描述】:
当input() 方法的值是myList 列表的一部分时,我想打印该值。我想获取input() 的值并在不使用变量的情况下打印它
myList = ["Banana", "Apple", "Lemon","Strawberry"]
if input() in myList:
print(input())
else:
print("Not found")
print(input()) 行没有得到输入的值。如果它在myList中,我想得到这个值
【问题讨论】:
-
你不能。
input()返回输入的字符串。如果你以后想用它,你必须把它放在某个地方 -
必须使用变量,别无选择
-
您的第一个 input() 从用户那里获取输入并检查列表。但是,您再次调用 input() 方法,因此这是一个新的输入实例,与之前的输入不匹配。如果要引用前一个,则必须将其存储到变量中,然后检查
-
如以上链接中所述
The result of an input() is an unnamed temporary variable that exists only until the full expression is evaluated. Once the + is executed, the temporary variables are effectively lost (and will be garbage collected eventually).在您的情况下,当您的语句移出 if 语句检查时,即使代码进入 if 语句,临时变量也会有效丢失跨度>
标签: python-3.x user-input