我需要x是一个整数,这样我的下一部分代码就可以工作了,但一旦我删除了0,1或2左右的引号,其中写着"使输入对计算机可读",我就会收到这个错误消息。
from random import randint
# Input
print("Rock: R Paper: P Scissors: S")
x = input("Please pick your choice: ")
y = randint(0,2)
#Making input readable for computer
if x.lower() == "r":
x = 0;
if x.lower() == "p":
x = "1";
if x.lower() == "s":
x = "2";
print("value entered ", x, "value generated ", y)
if (x == y):
print("It's a draw!")
# Calculating "Who wins?"
if x == 0 and y == 1:
print("Computer wins!")
if x == 0 and y == 2:
print("You won!")
if x == 1 and y == 0:
print("You won!")
if x == 1 and y == 2:
print("Computer wins!")
if x == 2 and y == 0:
print("Computer wins!")
if x == 2 and y == 1:
print("You won!")
您应该在此处使用elif
:
if x.lower() == "r":
x = 0
elif x.lower() == "p":
x = 1
elif x.lower() == "s":
x = 2
否则,每次运行都会评估所有三个条件。这意味着,如果第一个通过,那么x
将是第二个的整数。
此外,你应该这样写你的代码:
x = x.lower() # Put this up here
if x == "r":
x = 0
elif x == "p":
x = 1
elif x == "s":
x = 2
这样,就不会多次调用str.lower
。
最后,Python不使用分号。
将x赋给整数后,将调用x.lower()。
此外,您可能不应该对整数和输入字符串使用相同的变量。
使用两个字典,此代码将简洁明了:
x_conversion = {'r':0, 'p':1, 's': 2}
x = x_conversion[x.lower()]
或列出(在这种特殊情况下)
x_conversion=['r', 'p', 's]
x = x_conversion.index(x.lower())
对于获胜者
winner_choice = {(0,1): 'Computer', (1, 2): 'You', ...}
winner = winner_choice[(x, y)]
别忘了试试/except,你会在更短、更可读的代码中得到结果
iCodez的答案是唯一的,但如果您没有使用数字转换来对打印语句进行因子转换,则应该只使用字符串,如以下所示,而不是两者都使用。
编辑:必须更改y是什么,oops
x = raw_input("Please pick your choice: ").lower()
y = choice(['r','p','s'])
if (x == y):
print("It's a draw!")
# Calculating "Who wins?"
if x == 'r' and y == 'p':
print("Computer wins!")
elif x == 'r' and y == 's':
print("You won!")
elif x == 'p' and y == 'r':
print("You won!")
elif x == 'p' and y == 's':
print("Computer wins!")
elif x == 's' and y == 'r':
print("Computer wins!")
elif x == 's' and y == 'p':
print("You won!")
现在,如果你想转换成整数,那么你可以使用这个:
y = randint(0,2)
if x == "r":
x = 0
elif x == "p":
x = 1
elif x == "s":
x = 2
print ['tie', 'you win', 'they win'][x-y]
Python中不需要分号,但如果您觉得舒服的话,仍然可以使用分号。
编辑:只是为了好玩。
import random
pick = ['r', 'p', 's']
x = ""
while x not in pick:
x = str(raw_input("r, p, or s? ")).lower()
print ['tie', 'y win', 'y win', 'x win', 'x win'][ord(x)-ord(random.choice(pick))]
使用raw_input()代替输入。
这也应该是:
如果x.lower()=="r":x="0"