Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I limit user input length on python?

Tags:

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 limit it so it wont allow them to enter more than 5 characters?

I don't want something like this where it allows you to input more than 5 but will loop.

while True:
amt = input("Please enter the amount to make change for: $")
if len(amt) <= 5:
        print("$" + amt)
        break

I want complete restriction from entering more than 5 characters

like image 890
Cherry Avatar asked Mar 01 '19 21:03

Cherry


1 Answers

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 

def input_amount(message): 
    try: 
        stdscr = curses.initscr() 
        stdscr.clear() 
        stdscr.addstr(message) 
        amt = stdscr.getstr(1,0, 5) # or use getkey() as showed above.
    except: 
        raise 
    finally: 
        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())
like image 187
Sameh Farouk Avatar answered Oct 20 '22 17:10

Sameh Farouk