【问题标题】:i want to create a random number generator with a try counter but it said "cant assign to operator" here is what i have so far我想创建一个带有尝试计数器的随机数生成器,但它说“无法分配给操作员”这是我到目前为止所拥有的
【发布时间】:2016-12-05 18:56:16
【问题描述】:

我想创建一个带有尝试计数器的随机数生成器,但它说“无法分配给操作员”这是我目前所拥有的

  import random
    number=random.randint(1,10)
    print ("i am thinking of a number between 1 and 10")
    counter=5
    while counter>0:
        if number==int(input("guess what the number is:  ")):
            print("well done")
        else:
            counter-1=counter #it displays it hear before the 1st counter
            print ("your bad try again")
    print ("it was" ,number,)

【问题讨论】:

  • counter-1=counter - 你认为那会怎样?

标签: python revision


【解决方案1】:

可能是因为

counter-1=counter 

但您应该发布格式清晰的代码,以便轻松查看错误所在!

【讨论】:

    【解决方案2】:

    你不能修改变量名:

     import random
        number = random.randint(1, 10)
        print("i am thinking of a number between 1 and 10")
        counter = 5
        while counter > 0:
            if number == int(input("guess what the number is:  ")):
                print("well done")
            else:
                counter = counter - 1 # you cant modify a variable name
                print("your bad try again")
        print("it was", number, )
    

    输出:

    i am thinking of a number between 1 and 10
    guess what the number is:  5
    your bad try again
    guess what the number is:  4
    your bad try again
    guess what the number is:  3
    your bad try again
    guess what the number is:  2
    your bad try again
    guess what the number is:  1
    your bad try again
    it was 7
    

    【讨论】:

      【解决方案3】:

      您的代码的问题在于如何减少 counter 变量。

      这里是for 循环的更好解决方案。它会为您递减。

      import random
      number=random.randint(1,10)
      print ("I am thinking of a number between 1 and 10")
      print ("Guess what the number is - ",end='')
      for __ in range(5):
          if number==int(input()):
              print("well done")
              break
          else:
              print ("your bad try again")
      print ("Number was " ,number)
      

      【讨论】:

        猜你喜欢
        • 2014-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多