Formatting multi line strings in Python

Viewed 1985

Using this Pseudocode:
1. Declare Number As Float
2. Declare Root As Float
3. Declare Response As Character
4. Write Do you want to find the square root of a number?
5. Write Enter ‘y’ for yes, ‘n’ for no:


What I have coded:

Response = str(input('Do you want to find the square root of a number? \ 
       Enter y for yes, n for no: '))

Output in PyCharm Run Window:

Do you want to find the square root of a number? Enter y for yes, n for no:

Format Result wanted:

Do you want to find the square root of a number?            
Enter y for yes, n for no:
4 Answers

You can print a line wrap with \n.

Example:

Response = input('Do you want to find the square root of a number?\nEnter y for yes, n for no: ')

Output:

Do you want to find the square root of a number?
Enter y for yes, n for no: 

Your almost there. You just missed a '\n' in your string that your trying to print. This prints your string in the right format:

Response = str(input('Do you want to find the square root of a number?\nEnter y for yes, n for no: '))

You could use a newline character as said by @MikeScotty, or you could define the message first using a multi-line string. This makes changing and creating the message easier than typing in \n over and over again.

To do this, use triple-quoted strings:

m = """Do you want to find the square root of a number?
Enter y for yes, n for no: """

and then you can simply do:

input(m)

Which would prompt the user with:

Do you want to find the square root of a number?
Enter y for yes, n for no: [their entry ready here]

Of course, you don't need to define m (the message) separately, you can just write that triple-quoted string directly as the parameter for input, but things can start to get a bit messy:

Response = input("""Do you want to find the square root of a number?
Enter y for yes, n for no: """)

You need to add \n not just \ . N represent the 'new line'.

Related