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
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With