2
import random

def main():
    the_number = random.randint(1,100)
    guess = 0
    no_of_tries = 0
    while guess != the_number:
        no_of_tries += 1
        guess = int(input("Enter your guess: "))
        if guess < the_number:
            print "--------------------------------------"
            print "Guess higher!", "You guessed:", guess
            if guess == the_number - 1:
                print "You're so close!"
        if guess > the_number:
            print "--------------------------------------"
            print "Guess lower!", "You guessed:", guess
            if guess == the_number + 1:
                print "You're so close!"
        if guess == the_number:
            print "--------------------------------------"
            print "You guessed correctly! The number was:", the_number
            print "And it only took you", no_of_tries, "tries!"

if __name__ == '__main__':
    main()

现在,在我的随机数猜谜游戏中,如果一个人猜出一个数字更低或更高,他们会收到以下消息:

Guess lower! You guessed: 33
You're so close!

但我想把它写成一句话。

例如:

Guess lower! You guessed: 33. You're so close!

我将如何在我的代码中实现这一点?谢谢!

4

1 回答 1

6

如果您想避免它进入下一行,只需在语句后加一个逗号 ( ',') 。print例如:

print "Guess lower!", "You guessed:", guess,
                                           ^
                                           |

下一条print语句将在这一行的末尾添加它的输出,即,它不会像您当前所拥有的那样向下移动到下一行的开头。

更新以下评论

为了避免逗号引起的空格,您可以使用打印功能。IE,

from __future__ import print_function  # this needs to go on the first line

guess = 33

print("Guess lower!", "You guessed:", guess, ".", sep="", end="")
print(" You're so close!")

这将打印

Guess lower!You guessed:33. You're so close!

这个PEP还谈到了打印功能

于 2012-07-16T23:50:02.987 回答