简体   繁体   中英

else & elif statements seems that is not working in Python

I'm traying to make a simple rock paper scissors game but it seems that the if and elif statement do not respond. It only print s the else statement.

Here's the code:

from random import randint

rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''
t = [rock, paper, scissors]

player = int(input("choose 0 for rock and 1 for paper and 2 for scissors \n"))
cpu = t[randint(0,2)]

print(t[player])
print(cpu)  

if player == 0 and cpu == 2:
  print("YOU WIN")

elif cpu == 0 and player == 2:
  print("YOU LOSt")

elif player == 1 and cpu == 0:
  print("you win")

elif cpu == 1 and player == 0:
  print(" YOU LOST")

else:
  print("this is invalid input! ")  

I think you want cpu = randint(0,2) so that it's just the int. Then later when you need the string, replace cpu with t[cpu]

change this line cpu = t[randint(0,2)] to this cpu = randint(0,2)

As others mentioned, you need to change the two lines to:

cpu = randint(0,2)
print(t[player])
print(t[cpu]) 

By the way, there is a simple way to determine the outcome without if-statements:

from random import randint

rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''

outcome = ["DRAW", "YOU LOST", "YOU WON"]
t = [rock, paper, scissors]

player = int(input("choose 0 for rock and 1 for paper and 2 for scissors \n"))
cpu = randint(0, 2)
result = (cpu - player) % 3

print(t[player])
print(t[cpu])  
print(outcome[result])

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