1

I want input data in python but while inputting data,on the right side must be output for example, kilogram:

simple code:

weight = float(input('Enter your weight: (kg)'))

Output:

Enter your weight: some_number (kg) 

I want that kg stands always on right side of number while inputting data. I think question is clear if something not please let me know.Thank you in advance!

8
  • 3
    You can print your prompt, some spaces and "kg" and then move the cursor back to those spaces. Test this and adjust your string: print("aaaaaaaaaaaaaa\r\tbb") - \r is \carriage return\ which gets you back to the beginning(!) of the current line, \t is a tab character. Commented Aug 1, 2019 at 10:16
  • 1
    @h4z3 do note that if you are using something like pycharm, the console window is emulated so it wont show up correctly Commented Aug 1, 2019 at 10:21
  • 2
    Possible duplicate of Python: How do I get user input in the middle of a sentence (fill-in-the-blank style) using the input function? Commented Aug 1, 2019 at 10:23
  • 1
    why can't you just put the units in you input like this weight = float(input('Enter your weight (kg): '))? Commented Aug 1, 2019 at 10:31
  • 1
    in console's programs it is natural to have (kg) on left before : - Enter your weight (kg): some_number. Commented Aug 1, 2019 at 10:39

1 Answer 1

1

If you dig around, you'll find various versions of something called getch. This uses code from py-getch:

import sys

try:
    from msvcrt import getch
except ImportError:
    def getch():
        import tty
        import termios
        fd = sys.stdin.fileno()
        old = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            return sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old)

ascii_numbers = [ord('0') + x for x in range(10)]
weight = 0.0
while True:
    message = f"Enter your weight: {weight:9.2f} (kg)"
    sys.stdout.write("\r" + message)
    sys.stdout.flush()
    c = ord(getch())
    if c == 13:
        break
    elif c in ascii_numbers:
        c = c - ord('0')
        weight = (weight * 10) + (float(c) / 100)
    elif c == 127:
        weight = weight / 10
print("")

This is ugly, but my last experience with ncurses was even uglier.

Warning

This program ignores Ctrl-C inside the getch call. It is possible to modify this code so that the only way to stop the program is to kill the process. Sorry.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.