vendredi 28 mai 2021

Error executing while-loop "Loop being escaped randomly" Python

I have this code that is made for a game similar like (Rock, Paper, Scissors). When the code starts running, sometimes it gives error in not running the actual loop and conditions correctly. For example when the code starts running, at the first time the loop runs normally:

Foot, Nuke or Cockroach? (Quit ends): Foot
You chose: Foot
Computer chose: Foot
It is a tie!
Foot, Nuke or Cockroach? (Quit ends): 

But if I re-run the code again, the while-loop does not get executed as in the following example:

Foot, Nuke or Cockroach? (Quit ends): Cockroach
Foot, Nuke or Cockroach? (Quit ends): 

Or it gives me elif condition that the input is incorrect even though the input is from the correct selection.

Here is the full code:


    import random
    
    def main():
        rounds = 0
        win = 0
        tie = 0
        choices = ["Foot", "Nuke", "Cockroach"]
        cpu = random.choice(choices)
    
        while True:
    
            inpt = input("Foot, Nuke or Cockroach? (Quit ends): ")
    
            if inpt == "Foot" and cpu == "Nuke" or inpt == "Cockroach" and \
                    cpu == "Foot":
                print(f"You chose: {inpt}")
                print(f"Computer chose: {cpu}")
                print("You LOSE!")
                rounds += 1
    
            elif inpt == "Nuke" and cpu == "Foot" or inpt == "Foot" and \
                    cpu == "Cockroach":
                print(f"You chose: {inpt}")
                print(f"Computer chose: {cpu}")
                print("You WIN!")
                rounds += 1
                win += 1
    
            elif inpt == "Foot" and cpu == "Foot" or inpt == "Cockroach" and \
                    cpu == "Cockroach" or inpt == "Nuke" and cpu == "Nuke":
                print(f"You chose: {inpt}")
                print(f"Computer chose: {cpu}")
                print("It is a tie!")
                rounds += 1
                tie += 1
    
            elif inpt == "Quit":
                print(f"You played {rounds} rounds, and won {win} rounds, "
                      f"playing tie in {tie} rounds.")
                break
    
            elif inpt != "Foot" and inpt != "Cockroach" and inpt != "Nuke":
                print("Incorrect selection.")
    
    
    if __name__ == "__main__":
        main()




Aucun commentaire:

Enregistrer un commentaire