473,606 Members | 2,825 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Validate user input

11 New Member
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
4 2719
BeatSlayer
1 New Member
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 New Member
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 Recognized Expert Contributor
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 Recognized Expert Contributor
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
1664
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 used to do this as it doesn't appear that 1.1 includes this functionality itself. I am interested to know if anyone has a simple vb.net example of a solution to either of these issues. I'm new to regular expressions but if I have a working...
3
2321
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 page types can use? Is that the best approach? Would I simply use pattern matching to validate strings and/or remove any unwanted characters? Thanks in advance.
2
6666
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 them to retry. I am really lost on this one, and I really need some help. Thanks so much!! #include <iostream> #include <iomanip> #include <cmath> #include <cctype> #include <string> #include <sstream> using namespace std;
29
2521
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
4957
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' cannot be converted to type 'Date'. " <asp:TextBox ID="txtQDate" runat="server" Enabled="False"></asp:TextBox>
7
2233
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 '+' Characters other than these will not be allowed If a user enters characters other than the mentioned above , the alert message should be displayed
0
1018
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 using directly interface of the web service meanse i am running .asmx page now it shows 1 method Add on clicking Add link it will ask for two parameter a and b now of i enter string in that parameter instead of integer it throws an exception page. which...
1
1475
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 fine. However, when I enter some letters, php returns an ugly error. Is there a way to prevent the user from entering letters? Thanks!
12
2076
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 thats not something i want to implement. 2.I suppose my input line oriented . 3.The maximum columns i need is 80 4.There is an infinite loop in the program :) 5.I have *not* tried to validate the data as yet.
0
8045
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7981
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8467
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8320
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6803
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5994
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5470
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3952
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2458
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.