为什么当我更改我分配的号码时值没有改变?

Why is the value not changing when I change the number I assign?

我正在使用 getch() 进行一个简单的项目。当我应用变量 'door' 时,它只设置为 door1.

 if getch()==(' '):
  clicks+=1 
  money += door
  print("$ =", money, ((clicks-100)*-1), "clicks remaining", door, door1, door2, door3)

 if getch()==('1'):
  door=door1
  clicks +=1
  print("door 1 chosen,",((clicks-100)*-1), "clicks remaining", door, door1, door2, door3)

if getch()==('2'):
  door=door3
  clicks+=1
  print("door 2 chosen, -1 clicks",((clicks-100)*-1), "clicks remaining", door, door1, door2, door3)

if getch()==('3'):
  door=door3
  clicks+=1
  print("door 3 chosen, -1 click",((clicks-100)*-1), "clicks remaining", door, door1, door2, door3)

计算机正在读取我选择了另一扇门。它打印我要求它打印的内容并更改点击次数,但 'door' 的值仍然等于 'door1' 的值。我不完全明白为什么。

顺便说一句,(我不知道这是否相关)我发布的代码都在 while True 循环中。

尝试将您的代码和结构更改为:

from getch import getch

#Read input data/values

str=getch()

#Make your conditions that depends on Input value(str)

if str==(' '):
  clicks+=1 
  money += door

 elif str=('1'):
  door=door1
  clicks +=1

elif str==('2'):
  door=door3
  clicks+=1

elif str==('3'):
  door=door3
  clicks+=1

任何时候您发现自己在重复这样的代码,都有更好的方法。例如,考虑这个序列,它(我相信)做了你想做的事情,但是可以在不复制一堆代码的情况下进行扩展:


doors = [50,50,9000]
clicks = 0

while clicks < 100:
    ch = getch()

    if ch == ' ':
        money += door
        print("$", money,end='')
    else:
        door=doors[int(ch)-1]
        print("door",ch,"chosen,", end='') 

    clicks+=1 
    print(100-clicks, "clicks remaining", door, door1, door2, door3)