Python 2.7 我怎样才能加上一句;欺诈代码“;猜猜我有多少密码?

Python 2.7 我怎样才能加上一句;欺诈代码“;猜猜我有多少密码?,python-2.7,random,while-loop,Python 2.7,Random,While Loop,下面我有一段代码,其中随机选择了三个数字,用户有10次尝试解决代码。我想添加一个作弊代码(也就是说),让用户无需猜测三位数就可以进入下一个类/函数 我尝试在猜测时在之后添加或guess=='cheat'编码和猜测

下面我有一段代码,其中随机选择了三个数字,用户有10次尝试解决代码。我想添加一个作弊代码(也就是说),让用户无需猜测三位数就可以进入下一个类/函数

我尝试在猜测时在
之后添加
或guess=='cheat'
编码和猜测<10
。我试着将
if guess==code:
转换成
elif guess==code
并在elif之前添加一个
if guess==cheat'
。我是个书呆子,我的学习来源说我的目标可以用一行两个字来实现。我迷路了

 code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
 guess = raw_input("[keypad]> ")
 guesses = 0

 while guess != code and guesses < 9:
        print "WRONG!"
        guesses += 1
        guess = raw_input("Guess 3 numbers> ")

    if guess == code:
        print "Correct!"
        return my_func()
    else:
        print "Game over"
        return exit()
code=“%d%d%d”%(randint(1,9)、randint(1,9)、randint(1,9))
猜测=原始输入(“[键盘]>”)
猜测=0
猜猜看!=编码和猜测<9:
打印“错!”
猜测+=1
猜测=原始输入(“猜测3个数字>”)
如果guess==代码:
打印“正确!”
返回我的函数()
其他:
打印“游戏结束”
返回出口()

首先,确保代码缩进正确。既然你有它的工作,它似乎只是一个格式化问题的问题

有点不清楚这个作弊代码是什么,但我认为它是两件事之一:要么是单词作弊,要么是其他字符串。无论哪种方式,它都可以存储在名为
cheat
的变量中,当猜测是
code
cheat
时,您可以退出while循环

cheat = 'cheat'

while guess not in [code, cheat]:
还不清楚的是,当使用
欺骗时会发生什么情况,有两种可能的情况:

  • 作弊
    以输球结束游戏

    code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
    cheat = 'cheat'
    guess = raw_input("[keypad]> ")
    guesses = 0
    
    while guess not in [cheat, code] and guesses < 9:
        print "WRONG!"
        guesses += 1
        guess = raw_input("Guess 3 numbers> ")
    
    if guess == code:
        print "Correct!"
        return my_func()
    else:
        print "Game over"
        return exit()
    

  • 谢谢数字1不起作用,但数字2起作用。还有为什么在[cheat,code]中用括号括起
    而不是(cheat,code):
    中的
    ?方括号表示python列表,圆括号表示元组。这两种数据结构都适用于您的情况。
    
    code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
    cheat = 'cheat'
    guess = raw_input("[keypad]> ")
    guesses = 0
    
    while guess not in [cheat, code] and guesses < 9:
        print "WRONG!"
        guesses += 1
        guess = raw_input("Guess 3 numbers> ")
    
    if guess in [cheat, code]:
        print "Correct!"
        return my_func()
    else:
        print "Game over"
        return exit()