[Tutor] While Loop?
Alan Gauld
alan.gauld at btinternet.com
Wed May 14 18:14:35 CEST 2014
On 14/05/14 10:45, Sam Ball wrote:
> I'm attempting to create a program where the user inputs their account
> number (which must be 8 digits) and if what the user enters is not 8
> digits in length I want python to tell the user this is invalid and then
> keep asking for the account number until a suitable number has been entered.
> I'm guessing it's a sort of while loop
You guess correct
> userAccountNumber = eval(input("Please Input Your Account Number:"))
But please don;t do this. it is a huge security hole since whatever your
user enters will be executed as Python code - thats what eval() does.
Your user can ytype anything in there.
The correct approach is to use raw_input (since you seem to be using
Pthon v2) and a conversion function such as int() to get the data
type that you want.
> while userAccountNumber > 100000000 or <=9999999:
Python sees this as:
while (userAccountNumber > 100000000) or <=9999999:
Which makes no sense.
In most programming languages you test this like this:
(userAccountNumber > 100000000) or (userAccountNumber <= 9999999):
But in Python you can do these compound checks more
succinctly like this:
> while not (9999999 < userAccountNumber < 100000000):
And the other way is to check the length of the input at source:
userAccount = ''
while len(userAccount) != 8:
userAccount = raw_input("Please Input Your Account Number:")
userAccountNumber = int(userAccount)
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list