[Tutor] How to check if user input is an integer

Shall, Sydney sydney.shall at kcl.ac.uk
Fri Mar 29 13:21:38 CET 2013


On 29/03/2013 11:39, Amit Saha wrote:
> On Fri, Mar 29, 2013 at 9:35 PM, Amit Saha <amitsaha.in at gmail.com> wrote:
>> On Fri, Mar 29, 2013 at 9:33 PM, Ghadir Ghasemi
>> <ghasemmg01 at leedslearning.net> wrote:
>>> Hi guys I am trying to create part of a vending machine. The section below is if the user wants to insert 50p coins. It works but when I entered a non integer like 'dfsdf', the program just broke. Is there a way that the program can check if the input is an integer, and if it is, then the program does all the calculations, but if it isn't the program just keeps asking for an input? Thanks. Here is the section.
>>>
>>> fiftypencecoins = int(input("how many 50p coins do you want to insert or press 'e' to exit : "))
>>> if fiftypencecoins == 'e':
>>>          break
>>> else:
>>>       currentmoney += fiftypencecoins * 5/10
>>>       print("your newly updated credit is £" + str(currentmoney) + "0")
>> Is this Python 3 or Python 2 ?
> May be that's not relevant. So anyway, if you want to see whether the
> int() function will be successful on your input, you need to check
> whether the input constitutes of only digits.
>
> I can think of two ways:
>
> 1. Easy and naive way: for each character in the input, check whether
> it is between [0-1]
> 2. Use regular expressions: http://docs.python.org/2/library/re.html
>
> -Amit.
>
>
or;
where x is the input == fiftypencecoins;

return isinstance(x, int)

will return True or False

Then you can proceed as you wish.

-- 
Professor Sydney Shall,
Department of Haematological Medicine,
King's College London,
Medical School,
123 Coldharbour Lane,
LONDON SE5 9NU,
Tel & Fax: +44 (0)207 848 5902,
E-Mail: sydney.shall,
[correspondents outside the College should add; @kcl.ac.uk]
www.kcl.ac.uk

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130329/de52e963/attachment-0001.html>


More information about the Tutor mailing list