简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM