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()

Right now, in my random number guessing game, if a person guesses lower or higher by one number, they receive the following message:

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

But I want to make it one sentence.

For example:

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

How would I implement this in my code? Thanks!

1 Answer 1

6

Simply put a comma (',') after your print statement if you want to avoid it advancing to the next line. For example:

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

The next print statement will add its output at the end of this line i.e., it will not move down to the start of the next line as you currently have.

Update re comment below:

To avoid the space due to the comma, you can use the print function. I.e.,

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!")

This will print

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

This PEP also talks about the print function

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but if want to put a period before the message, like ". You're so close!", wouldn't there be a gap between 33 and .? Is there a way to concatenate them?
+1. The other advantage of using the print function is that your code is valid Python 3 as well as Python 2. (PS, you might want to remove the space between the print and the parens for consistency with the OP's code, and because Guido says so…)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.