无法根据Python中的不同语句将我的代码打印出来

时间:2015-08-18 02:21:21

标签: python

我已经尝试了其他和elif语句,但没有任何想法?

import random


choice = input(" Witch one did u pick Rock , Paper or Scissors?")
print(choice)


computer = ["R", "P", "S"]
print(random.choice(computer))


if choice == "R" and random.choice(computer) == "R":
    print("Sorry its a tie")

if choice == "R" and random.choice(computer) == "P":
        print("Sorry Will wins")

2 个答案:

答案 0 :(得分:2)

你不应该每次都调用random.choice(computer),这可以在对函数的不同调用中给出不同的结果。您应该只调用一次,然后保存该结果并在if..elif中使用它。您还应该使用if..elif,而不是if..if

import random

choice = input(" Witch one did u pick Rock , Paper or Scissors?")
print(choice)
import random
computer = ["R", "P", "S"]
choosen = random.choice(computer)
print(choosen)


if choice == "R" and choosen == "R":
    print("Sorry its a tie")
elif choice == "R" and choosen == "P":
        print("Sorry Will wins")

答案 1 :(得分:1)

让我们从顶部开始。首先你说:

choice = input("Witch one did u pick Rock, Paper or Scissors?)
print(choice)

因为您正在打印此决定,所以可能有助于用户体验和调试来编写:

print("User Choice: " + choice)

继续前进:

computer = ["R", "P", "S"]
print(random.choice(computer))

从用户的角度来看,如果您要打印出来,您希望匹配与之前相同的样式并写下:

computer = ["Rock", "Paper", "Scissors"]

从编程的角度来看,您将要将随机选择的结果保存在变量中,以便稍后使用它,因为再次调用random.choice将创建新的答案。所以接近这个的好方法是:

computerDecision = random.choice(computer)
print("Computer Choice: " + computerDecision)

最后你有if语句。首先你要检查:

if choice == "R"

在您编写的代码中,问题就出现了:

choice = input(" Witch one did u pick Rock , Paper or Scissors?")

意思是输出很可能是(“Rock”,“Paper”或“Scissors”)而不是(“R”,“P”或“S”),所以你会想要:

if choice == "Rock"

并且你使用相同的if语句两次,这样你就可以只做一个嵌套的if并使用你之前的变量:

if choice == "Rock":
    if computerDecision == "Rock":
        print("Sorry its a tie")
    elif computerDecision == "Paper":
        print("Sorry Will wins")
    elif computerDecision == "Scissors":
        print("You win")
    else:
        print("Invalid input")

你需要为“纸”和“剪刀”制作这个。 最后的其他陈述只是涵盖了用户输入“Rock”,“Paper”或“Scissors”之外的东西的场景