【问题标题】:How to change the value of somthing through input in python如何通过python中的输入更改某物的值
【发布时间】:2022-08-19 16:44:13
【问题描述】:

我想要做的是,当你输入“Y”时,它会将键的值从 0 更改为 1。我对 python 相当陌生,我尝试过使用 SET 函数,但它没有奏效。这是我的代码:

 key = 0

 if key==0:
     print(\"Would you like to pick up the key\")
     choice = input(\"\")
     if choice==\"Y\":
         set(key=1)
  • 只需覆盖变量,删除集合并仅保留key=1
  • 运行此程序时是否注意到 TypeError 异常?你怎么看放()做?
  • set 创建一个称为集合的数据结构,它是对象的无序集合。它不会将 key 的值设置为 1。你只需要一个 = 来给某个东西一个值
  • 欢迎,您可以直接设置键变量key=1而不是set(key=1),让您的python之旅尽可能好地从一本好书开始,例如amazon.co.uk/dp/1593279280

标签: python


【解决方案1】:

您想将 1 分配给变量钥匙如果输入是 'Y' 否则你希望它是 0

所以:

key = 1 if input('Would you like to pick up the key') == 'Y' else 0

【讨论】:

    【解决方案2】:

    给它赋值

    key = 1
    

    顺便说一句,在python中你可以做到这一点

    input("Would you like to pick up the key")
    

    我认为您应该先了解基础知识。在这样的随机教程中花几分钟时间

    https://www.w3schools.com/python/

    【讨论】:

      【解决方案3】:
      key = 0
      if key==0:
          print("Would you like to pick up the key")
          choice = input("")
          if choice=="Y":
              key=1
      print('Key',key)
      

      【讨论】:

        【解决方案4】:

        我希望你想在这里做这件事。

        key = 0
        
        if key==0:
            print("Would you like to pick up the key")
            choice = input("")
            if choice=="Y":
                key = 1
        
        print(key)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-03
          • 2020-03-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-06-25
          • 1970-01-01
          • 2021-12-12
          相关资源
          最近更新 更多