import random as rand
import string
string.letters='rps'
comp = rand.choice(string.letters)
user = input("enter r for rock,p for paper,s for scissors\n")
print(comp)
if comp==user:
print("its a tie")
elif comp==r and user==p:
print(" congrats you won ")
elif comp==r and user==s:
print("sorry you lost")
elif comp==p and user==r:
print("sorry you lost")
elif comp==p and user==s:
print(" congrats you won ")
elif comp==s and user==p:
print("sorry you lost")
elif comp==s and user==r:
print(" congrats you won ")
在输出中我收到以下错误:
enter r for rock,p for paper,s for scissors
s
r
Traceback (most recent call last):
File "rpcs.py", line 12, in <module>
elif comp==r and user==p:
NameError: name 'r' is not defined
任何帮助都会非常感谢你
答案 0 :(得分:2)
将r
替换为'r'
。 Python正在阅读您作为名为r
的变量编写的r
,并将其视为字符串。对p
,s
等进行同样的操作....
答案 1 :(得分:0)
您可以尝试这样:
import random as rand
import string
string.letters='rps'
comp = rand.choice(string.letters)
user = input("enter r for rock,p for paper,s for scissors\n")
print(comp)
if comp==user:
print("its a tie")
elif comp == 'r' and user == 'p':
print(" congrats you won ")
elif comp == 'r' and user == 's':
print("sorry you lost")
elif comp == 'p' and user == 'r':
print("sorry you lost")
elif comp == 'p' and user == 's':
print("congrats you won")
elif comp == 's' and user == 'p':
print("sorry you lost")
elif comp == 's' and user == 'r':
print("congrats you won")
说明:
这些字符需要与quotes
一起使用。否则python将其作为变量。由于未使用引号,因此引发了错误NameError: name 'r' is not defined
答案 2 :(得分:0)
这不起作用,因为当您执行条件测试时,您不会输入字符串。以下是一个示例示例:
import random
strings = ['r', 'p', 's']
computer = strings[random.randint(0, 2)]
user_choice = input("enter r for rock,p for paper,s for scissors:\n")
if computer==user_choice:
print("its a tie")
elif computer == 'r' and user_choice == 'p':
print(" congrats you won ")
elif computer == 'r' and user_choice == 's':
print("sorry you lost")
elif computer == 'p' and user_choice== 'r':
print("sorry you lost")
elif computer == 'p' and user_choice == 's':
print(" congrats you won ")
elif computer == 's' and user_choice == 'p':
print("sorry you lost")
elif computer == 's' and user_choice == 'r':
print(" congrats you won ")
else:
print('Error')
请注意,在每个条件测试中,我们输入要比较的值作为字符串。如果它们不是字符串对象,则在此示例中无法比较它们。简单地放置p,r或s将不起作用,但是如你所见,它们需要用引号括起来。否则,您将收到回溯错误。