Skip to content Skip to sidebar Skip to footer

How Can I Limit User Input Length On Python?

amt = float(input('Please enter the amount to make change for: $')) I'd like the user to enter an amount in dollars and therefore allow 5 characters (00.00) Is there a way to limi

Solution 1:

use curses

there is other approaches but i think this is a simple one.

read about curses module

you can use getkey() or getstr(). but using getstr() is simpler, and it give the user choice to enter less than 5 char if he want, but no more than 5. i think that is what you asked for.

import curses
 stdscr = curses.initscr()
 amt = stdscr.getstr(1,0, 5) # third arg here is the max length of allowed input

but if you want to force 5 character , no less , no more, you may want to use getkey() and put it in for loop , in this example program will wait user to enter 5 character before continue , no need even to press return key.

amt = ''
stdscr = curses.initscr() 
for i in range(5): 
     amt += stdscr.getkey() # getkey() accept only one char, so we put it in a for loop

note:

you need to call the endwin() function to restore the terminal to its original operating mode.

A common problem when debugging a curses application is to get your terminal messed up when the application dies without restoring the terminal to its previous state. In Python this commonly happens when your code is buggy and raises an uncaught exception. Keys are no longer echoed to the screen when you type them, for example, which makes using the shell difficult.

putting all together:

going with first example, implementing getstr() method in your program could be like this:

import curses 

definput_amount(message): 
    try: 
        stdscr = curses.initscr() 
        stdscr.clear() 
        stdscr.addstr(message) 
        amt = stdscr.getstr(1,0, 5) # or use getkey() as showed above.except: 
        raisefinally: 
        curses.endwin() # to restore the terminal to its original operating mode.return amt


amount = input_amount('Please enter the amount to make change for: $') 
print("$" + amount.decode())

Post a Comment for "How Can I Limit User Input Length On Python?"