为什么我会得到“属性错误:'int'对象没有属性'lower'”?

时间:2013-12-04 22:11:26

标签: python string integer

我需要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!")

5 个答案:

答案 0 :(得分:3)

你应该在这里使用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不使用分号。

答案 1 :(得分:2)

在将x分配给整数后,您正在调用x.lower()。

此外,您可能不应对整数和输入字符串使用相同的变量。

答案 2 :(得分:0)

iCodez答案就是那个,但你应该只使用字符串,如下所示,如果你没有使用数字转换来计算你的print语句,而不是两者。

编辑:必须改变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))]

答案 3 :(得分:0)

有几个字典,这段代码简洁明了:

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)]

不要忘记尝试/除外,您将获得更短,更易读的代码

答案 4 :(得分:-2)

使用raw_input()而不是输入。

这也应该是:

如果x.lower()==“r”:     x = “0”