Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify input() type in Python?

Is it possible to define input times, like time, date, currency or that should be verified manually? Like for example:

morning = input('Enter morning Time:')
evening = input('Enter evening Time:')

.. I need (only) time here, how do I make sure that user enters input in xx:xx format where xx are integers only.

like image 519
eozzy Avatar asked Sep 13 '26 16:09

eozzy


2 Answers

input (in Python 2.any) will return the type of whatever expression the user types in. Better (in Python 2.any) is to use raw_input, which returns a string, and do the conversion yourself, catching the TypeError if the conversion fails.

Python 3.any's input works like 2.any's raw_input, i.e., it returns a string.

like image 145
Alex Martelli Avatar answered Sep 16 '26 05:09

Alex Martelli


You can't really force the input function to return a certain type. It's best you write some kind of a wrapper that reads some input from the user and then converts it to an appropriate type for your application (or throw an exception in case of an error).

Also, as Alex said, it's better to use raw_input for user input since it will always return the entered value as a string. Much more manageable.

like image 37
Noufal Ibrahim Avatar answered Sep 16 '26 06:09

Noufal Ibrahim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!