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

Time:04-26

I am working on a simple project using getch(). When I apply the variable 'door', it only sets to 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)

The computer is reading that I have selected a different door. It prints what I've asked it to print and changes the click count, but the value of 'door' continues to be equal to the value of 'door1'. I don't fully understand why.

Just as an aside, (I don't know if this is going to be relevant or not) the code I've posted is all under a while True loop.

CodePudding user response:

Try to change your code and structure to be :

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

CodePudding user response:

Anytime you find yourself repeating code like that, there is a better way. Consider, for example, this sequence, which (I believe) does what you were trying to do, but in a way that can be extended without duplicating a bunch of code:


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)
  • Related