简体   繁体   中英

Issues with counters in while loop Python

I'm currently having an issue in my code, in which I am attempting to create a rock paper scissors game. My counting method does not seem to work (when the program looped the win loss counters are both on 0), so I was hoping I could get some help. I am fairly new to Python and stack overflow, so bear that in mind. Sorry for the long wall of code:

import random
import time
win=0
loss=0
def compare():
  if choice == "rock" and opp == "paper":
    print("You lose!")
    loss+1
  elif choice == "paper" and opp == "scissors":
    print("You lose!")
    loss+1
  elif choice== "scissors" and opp == "rock":
    print("you lose")
    loss+1
  elif choice == "scissors" and opp == "paper":
    print("you win")
    win+1
  elif choice == "rock" and opp =="scissors":
    print("you win")
    win+1
  elif choice == "paper" and opp == "rock":
    print("you win!")
    win+1
  else:
    print("...")
op=["rock","paper","scissors"]
phrase=["Rock paper scissors shoot!","janken bo!", "pierre-feuille-ciseaux!","papier, kamień, nożyczki!"]

while True:
  print ("You have",win,"wins and",loss,"losses")
  choice=input(random.choice(phrase)).lower()
  if choice not in op:
    print("Rock paper or scissors")
    continue
  else:
    print()
  opp=random.choice(op)
  print (opp)
  compare()
  while opp==choice:
    choice=input(random.choice(phrase)).lower()
    time.sleep(1)
    opp=random.choice(op)
    print (opp)
    compare()

I appreciate any help. Thanks

Each time you write variable + 1 , you don't alter the variable. For example in :

def compare():
  if choice == "rock" and opp == "paper":
    print("You lose!")
    loss+1

loss+1 does nothing, ie the value is not assigned.

You need to assign the value to your variable. For example : loss += 1

Welcome to StackOverflow!

In your if statements you aren't actually incrementing the counts. You need to do win = win + 1 and loss = loss + 1

def compare():
  if choice == "rock" and opp == "paper":
    print("You lose!")
    loss = loss + 1

Now you can also do some "shorthand" syntax. loss += 1 is equivalent to loss = loss + 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM