Joel Deleep
Joel Deleep

Reputation: 1398

Add space before reading an input in python

I have a python program which works as a calculator.

import re


value = 0
run = True

while run:
    if value == 0:
        equation = input('Enter the equation ')
    else:
        equation=input(str(value))
        # print(equation + ' ')
    if equation == 'quit':
            run = False
    else:
        equation = re.sub("[a-zA-Z""]",'',equation)
        if value ==0:
            # equation=eval(equation)
            value=eval(equation)
        else:
            value=eval(str(value)+equation)
            print(equation + ' ')

The program works without problem , but when reading the input after the first iteration , the terminal is as below

python3 file.py
Enter the equation 10+10
20+30

The next input can be provided next to 20. I want to add a space before reading the input , so the output will be as shown below

python3 file.py
Enter the equation 10+10
20 +30

How can I add a space before reading the next input so the cursor will create a space

Example

input=input('Enter the input ')

Python Version : 3.7.7

Upvotes: 0

Views: 2559

Answers (2)

Thomas Weller
Thomas Weller

Reputation: 59259

IMHO, this line is not what you want:

equation=input(str(value))

Outputting the result of the calculation should be separate from the next input because of semantics. The argument to input() is the prompt to tell the user what to do. "20" (or whatever intermediate result) is not a good instruction for the user.

So the code becomes

print(value, end=" ")    # end=" " prevents a newline and adds a space instead
equation=input()         # don't give any prompt, if there's no need to

Upvotes: 2

L.Grozinger
L.Grozinger

Reputation: 2398

You may simply append a space to the string given to input.

In your example, changing the line equation=input(str(value)) to equation=input(str(value) + ' ') will produce your desired output.

Upvotes: 2

Related Questions