user11724121
user11724121

Reputation:

input data via console in python

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!

Upvotes: 1

Views: 185

Answers (1)

user3657941
user3657941

Reputation:

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.

Upvotes: 1

Related Questions