473,383 Members | 1,788 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Validate user input

11
I am requesting user input from a menu a script. The input I am requesting needs to be an integer. Is it possible to validate that the user actually entered an integer and not a string or just hit enter? Everything I have tried will give me
"File "<string>", line 0, in ?
NameError: name 'd' is not defined
The code I have looks like this:

Expand|Select|Wrap|Line Numbers
  1. def init_menu():
  2.   print '''
  3.   0) Exit
  4.   1) Environment
  5.   2) Use
  6.   3) OS
  7.   4) Arch
  8.   5) ALL
  9.   6) Done
  10.   '''
  11.   ROW = input("Choose your server type: [0]")
  12. #  ROW = ROW.strip()
  13.   print
  14. #  if len(ROW) == 0:
  15. #    print 'Exiting...'
  16. #    sys.exit(0)
  17.   if ROW == 0:
  18.     sys.exit(0)
  19.   elif ROW == 1:
  20.     print 'You have chosen by', INITIAL.get(ROW)
  21.   elif ROW == 2:
  22.     print 'You have chosen by', INITIAL.get(ROW)
  23.   elif ROW == 3:
  24.     print 'You have chosen by', INITIAL.get(ROW)
  25.   elif ROW == 4:
  26.     print 'You have chosen by', INITIAL.get(ROW)
  27.   elif ROW == 5:
  28.     print 'You have chosen', INITIAL.get(ROW)
  29.   elif ROW == 6:
  30.     print 'You are', INITIAL.get(ROW)
  31.   else:
  32.     sys.exit(0)
  33.   return ROW
The print statements for each choice are just place holders and will have actual actions associated with them eventually

Thanks,
John
Jun 1 '10 #1

✓ answered by dwblas

isdigit() will work fine for this. Note that it returns False for a float.
Expand|Select|Wrap|Line Numbers
  1. test_strs = [ "12345", " 0123", "123.45", \
  2.               "-123", "123x5", "12*67", " 12 45"]
  3. for eachstr in test_strs :
  4.     print "%7s" % eachstr,
  5.  
  6.     if eachstr.isdigit( ) :
  7.         print " IS",
  8.     else :
  9.         print " is NOT",
  10.     print "a digit" 

4 2696
Something like this maybe, I'm just a beginner so maybe theres a better option.



Expand|Select|Wrap|Line Numbers
  1. row = 0
  2.  
  3. while int(row) not in range(1,8):
  4.     row = raw_input('''
  5.         0) Exit
  6.         1) Environment
  7.         2) Use
  8.         3) OS
  9.         4) Arch
  10.         5) ALL
  11.         6) Done
  12.     : ''')
  13.  
  14. row = int(row)
Jun 1 '10 #2
ennoil
11
That does look better than my code but still errors if the user does not enter a number (or, more importantly for this) just hits enter.
Jun 1 '10 #3
dwblas
626 Expert 512MB
isdigit() will work fine for this. Note that it returns False for a float.
Expand|Select|Wrap|Line Numbers
  1. test_strs = [ "12345", " 0123", "123.45", \
  2.               "-123", "123x5", "12*67", " 12 45"]
  3. for eachstr in test_strs :
  4.     print "%7s" % eachstr,
  5.  
  6.     if eachstr.isdigit( ) :
  7.         print " IS",
  8.     else :
  9.         print " is NOT",
  10.     print "a digit" 
Jun 2 '10 #4
Glenton
391 Expert 256MB
In this case you want to do a bunch of tests, so I would invert the logic:

Expand|Select|Wrap|Line Numbers
  1. while True:
  2.     row = raw_input('''
  3.         0) Exit
  4.         1) Environment
  5.         2) Use
  6.         3) OS
  7.         4) Arch
  8.         5) ALL
  9.         6) Done
  10.     : ''')
  11.     if row="": continue
  12.     if isdigit(row) and row in range(1,7): break
Of course the if row="": continue bit isn't necessary, but I just include it in case you need the idea for something else.

Also, the "and" operator is a short-cut operator, meaning that the second part is only evaluated when the first part is True. Handy that, or you'd get an error...
Jun 2 '10 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: charleswesley | last post by:
I find myself regularly needing to validate user input as either a) numeric only or b) valid email address format (user@domain.tld) I am assuming that there are regular expressions that can be...
3
by: A TO Consultant | last post by:
Hi All, I am working on a web application that uses both asp classic and asp.net pages. We need to validate user input to avoid attacks like sql injection. Can a component be created that both...
2
by: promiscuoustx | last post by:
Hi again all!! I am trying to write my program below to validate user input. In other words, if the user inputs something like "1a2.34", I need to return a message that states invalid data and for...
29
parshupooja
by: parshupooja | last post by:
Hi, I am working in Asp.Net 2.0, SQL Server, C#. I am trying to create a User Input form which has lots of fields such as : salutation; Firstname: lastname: address: Zip: Phone:
1
by: Tamer Ibrahim | last post by:
Hi, I'm trying to validate user input date using range validator on a text box . This code is throwing this exception "The value 'DateTime.Now;' of the MaximumValue property of 'rvQDate'...
7
by: Amit | last post by:
Dear Friends I need to write a Java Script for a string payment_code which comes populated from a text field , should contain only 0-9,A-Z,a-z,Space ' ',Hyphen '-',Full stop '.',Comma ',',Plus...
0
by: Rohit111111 | last post by:
Hello all i have created a web service which consist a web method say Add(int a, int b) it takes two parameter a and b both are of type integer, now i have to validate the both parameter. I am...
1
by: ss112358 | last post by:
Hey all! I am making a very simple program which requires the user to enter a numerical value into a text box (html form) and then multiplies it by 10 before echoing back. The program is working...
12
by: Tarique | last post by:
I have tried to restrict the no. of columns in a line oriented user input.Can anyone please point out potential flaws in this method? btw.. 1.I have not used dynamic memory allocation because...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.