我不明白这句话

时间:2016-09-08 23:27:38

标签: python

我是学习Python的新手,这些天我提出了很多问题。我试图做公牛和奶牛比赛,但我失败了,然后我在网上搜索了代码。我找到了这句话,我不知道它的作用:

while True:
        guess = raw_input('\nNext guess [%i]: ' % guesses).strip()
        if len(guess) == size and \
           all(char in digits for char in guess) \
           and len(set(guess)) == size:
           break
        print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size

我不理解\,究竟是什么评估布尔值以及charall()中的含义还有一个\。我有点困惑。

我将把剩下的代码留在这里:

import random

digits = '123456789'
size = 4
chosen = ''.join(random.sample(digits,size))
#print chosen # Debug
print '''I have chosen a number from %s unique digits from 1 to 9 arranged in a random order.
You need to input a %i digit, unique digit number as a guess at what I have chosen''' % (size, size)

guesses = 0
while True:
    guesses += 1
    while True:
        # get a good guess
        guess = raw_input('\nNext guess [%i]: ' % guesses).strip()
        if len(guess) == size and \
           all(char in digits for char in guess) \
           and len(set(guess)) == size:
           break
        print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size
    if guess == chosen:
        print '\nCongratulations you guessed correctly in',guesses,'attempts'
        break
    bulls = cows = 0
    for i in range(size):
        if guess[i] == chosen[i]:
            bulls += 1
        elif guess[i] in chosen:
            cows += 1
    print '  %i Bulls\n  %i Cows' % (bulls, cows)

1 个答案:

答案 0 :(得分:1)

通常,python中的代码需要在一行上完成。相反,如果您希望使用换行符将表达式继续到下一行(最明显的原因是提高可读性),那么您可以在行的末尾插入\

这告诉python将下一行视为现有行的一部分。