【问题标题】:Using the value of the input() method without using a variable Python在不使用变量 Python 的情况下使用 input() 方法的值
【发布时间】: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


【解决方案1】:

正如我之前评论中所解释的,请查看输入语句的工作原理。

How print(input() + input()) works in python ? Without variable assignment?

这是从上述链接摘录到另一个类似问题:

  • input() 的结果是存在的未命名临时变量 仅在评估完整表达式之前。一旦 + 被执行, 临时变量实际上丢失了(并且将是垃圾 最终收集)。

本质上,您无法访问 input() 语句中的值,除非您将其存储到变量中。一旦您的代码超出if input() in mylist:,该值就会丢失。如果你想访问它,你需要存储它并使用它。

您能解释一下为什么不想将值存储到变量中吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-28
    • 2020-11-23
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2021-12-21
    • 2020-12-04
    相关资源
    最近更新 更多