colappse
colappse

Reputation: 69

How do I add a newline in python?

I recently made a simple game where the user guesses the program's favorite color. Almost everything is fine about the code but I just need to find a way to create a single piece of a newline to make it more readable. Any help will be appreciated!

Anyways, here is the code:

import random


def color_guess():
    color_sets = {
        'Green': 1,
        'Blue': 2,
        'Red': 3,
        'Yellow': 4,
    }

    user_name = input("Welcome! Please enter your username: ")

    print(user_name + " your goal is to guess my favorite color.")
    print("Your choices are: 'Red', 'Green', 'Blue', and 'Yellow'")

    favorite_color = random.choice(list(color_sets))

    guess = input("What do you think? ")

    if guess == favorite_color:
        print("Gg! You guessed my favorite color: " + favorite_color)

    else:
        print("Nope. It was: " + favorite_color)


color_guess()

When I add print("\n"), It creates 2 newlines instead of one. Is there a way to fix this?

Example:

Welcome! Please enter your username:


user_name your goal is to guess my favorite color. 


Your choices are: 'Red', 'Green', 'Blue', and 'Yellow'

And so on.

But I want it to be this way.

Welcome! Please enter your username:

user_name your goal is to guess my favorite color. 

Your choices are: 'Red', 'Green', 'Blue', and 'Yellow'

Etc.

Upvotes: 0

Views: 273

Answers (3)

Raphael Eckert
Raphael Eckert

Reputation: 118

Python adds a linebreak after each Print Statement automatically, so if you have a print Statement with ("\n") you have two linebreaks. there are 3 ways to solve this:

  1. add the line break to the end of all your print statements
print("Hello world\n")
print("Hello world\n")
  1. remove the automatic linebreak by setting the 'end' parameter to an empty string
print("Hello world", end = "")
print("\n")
print("Hello world")
  1. use an empty string as linebreak, because the print statement sets a linebreak anyway
print("Hello world")
print("")
print("Hello world")

Upvotes: 0

MatsLindh
MatsLindh

Reputation: 52902

You can use the end argument to the print function to get a different line ending - in this case, you can use it to get two newlines instead of one.

print("Gg! You guessed my favorite color: " + favorite_color, end="\n\n")

Another option is to use an empty print statement, but being explicit about having an extra newline is the way to go.

Upvotes: 2

Sentry
Sentry

Reputation: 4113

Either add the "\n" to the end of your existing print

print(user_name + " your goal is to guess my favorite color.\n")

or just use

print()

for a newline.

Upvotes: 1

Related Questions