我有一个数字猜谜游戏的代码,当我发现问题时,我正在播放它。
#猜数字
print("I'm thinking of a number between 1 and 20. Can you guess my number?")
r = str(input('{} please enter a integer between 1 and 10: '.format(name)))
r = str(input('{} please enter a integer between 1 and 10: '.format(name2)))
print (name, ' you chose ', r)
print (name2, ' you chose ', p)
r1 = random.randrange(10)
if r == p:
print('Plz choose different numbers from each other')
if r == r1:
print('Computer chose', r1,',',name,' Wins!')
if p == r1:
print('Computer chose', r1,',',name2,' Wins!')
elif (r > 'r1' and p < 'r1'):
print('Computer chose', r1, ' both of you lose')
elif (r < 'r1' and p < 'r1'):
print('Computer chose', r1, ' both of you lose')
elif (r > 'r1' and p > 'r1'):
print('Computer chose', r1, ' both of you lose')
elif (r < 'r1' and p > 'r1'):
print('Computer chose', r1, ' both of you lose')
当计算机读取这部分代码时
if r == p:
print('Plz choose different numbers from each other')
if r == r1:
print('Computer chose', r1,',',name,' Wins!')
if p == r1:
print('Computer chose', r1,',',name2,' Wins!')
elif (r > 'r1' and p < 'r1'):
print('Computer chose', r1, ' both of you lose')
elif (r < 'r1' and p < 'r1'):
print('Computer chose', r1, ' both of you lose')
elif (r > 'r1' and p > 'r1'):
print('Computer chose', r1, ' both of you lose')
elif (r < 'r1' and p > 'r1'):
print('Computer chose', r1, ' both of you lose')
它跳过了第一部分并继续说两名球员都输了。为什么会发生这种情况?我该如何解决?
答案 0 :(得分:2)
我认为问题在于:
r = str(input('{} please enter a integer between 1 and 10: '.format(name)))
r = str(input('{} please enter a integer between 1 and 10: '.format(name2)))
你不想第二次分配给p
吗? p = str(...
此外,这些方面没有多大意义:
elif (r > 'r1' and p < 'r1'):
print('Computer chose', r1, ' both of you loose')
elif (r < 'r1' and p < 'r1'):
print('Computer chose', r1, ' both of you loose')
elif (r > 'r1' and p > 'r1'):
print('Computer chose', r1, ' both of you loose')
elif (r < 'r1' and p > 'r1'):
print('Computer chose', r1, ' both of you loose')
您正在将r
和p
与字符串'r1'
进行比较。你可能想要与r1
本身进行比较,但即使这样,逻辑也很奇怪。我想你只想要if r != r1 and p != r1
,但下面的内容要简单得多:
if r == p:
print('Plz choose different numbers from each other')
elif r == r1:
print('Computer chose', r1,',',name,' Wins!')
elif p == r1:
print('Computer chose', r1,',',name2,' Wins!')
else:
print('Computer chose', r1, ' both of you loose')
(注意,这个单词拼写为&#34;输了。&#34;)
<强>更新强>
你可能想要整数:
r = int(input('{} please enter a integer between 1 and 10: '.format(name)))
r = int(input('{} please enter a integer between 1 and 10: '.format(name2)))