为什么不打印此变量?

时间:2018-11-07 19:29:20

标签: python

所以我正在为数学做这件事,需要详细的算法。问题是,它实际上不会打印出答案,我也不知道为什么。本质上,我们必须找到策略的游戏是这样的:我们有三张卡,每张卡的背面都有X或O(因此卡是XX,OO和XO)。我们必须根据卡正面的内容来猜测卡背面的内容。每次都洗牌,但是我仍然认为获得XX然后再次获得XX的几率很低。所以我编写了这段代码。

#math thing
#if the previous one was XX, don't choose XX next time
#if the previous was OO, don't choose OO next time
#if it was XO or OX, choose either O or X as the back
import random 
starter = input("What's on Front? (starter) ")
back = ""
starterBack = ("X", "O")
starter2 = random.choice(starterBack)
print(starter2)
front = input("What's on Front?")
if starterBack == 'X' and starter == 'X' and front == 'X':
  back = O
  print(back)
if starterBack == "O" and starter =="O" and front == "O":
  back = "X"
  print(back)
if starterBack == "O" and starter == "X" and front == "X":
  back = random.choice("O", "X")
  print(back)

但是它不会输出'back'变量。为什么?

3 个答案:

答案 0 :(得分:2)

if starterBack == 'X':

starterBack是一个元组,因此它不能等于字符串。要访问元组中的单个项目,请使用方括号将其编入索引:

starterBack[0]

这给出了第一项-记住,Python从零开始计数。给你:

if (starterBack[0] == 'X'
    and started == 'X'
    and front == 'X'):

答案 1 :(得分:0)

starterBack("X", "O"),因此if starterBack == 'X' ...if starterBack == 'O' ...条件永远不会为真,并且back将永远不会被打印。您可能是想在starter2条件下写starterBack而不是if吗?

答案 2 :(得分:0)

starterBack = ("X", "O") 

是一个元组,您无法比较像这样的值starterBack == "X",您需要在元组中提供特定的值索引,因为X处于0索引处,将其写入starterBack[0] == "X"并将back = O更改为back = "O"。并且还将back = random.choice(starterBack)元组作为参数而不是back = random.choice("X","O"). 试试这个代码。

import random 
starter = input("What's on Front? (starter) ")

starterBack = ("X", "O")
starter2 = random.choice(starterBack)
print(starter2)
front = input("What's on Front?")
if starterBack[0] == "X" and starter == "X" and front == "X":
    back = "O"
    print(back)
if starterBack[1] == "O" and starter =="O" and front == "O":
    back = "X"
    print(back)
if starterBack[1] == "O" and starter == "X" and front == "X":
    back = random.choice(starterBack)
    print(back)