473,779 Members | 2,023 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Basic Python Validation

1 New Member
Having difficulty creating error handling when inputting an integer

dvdQuant = input("Enter quantity of DVD: ")

how can I get python to return a print "Error Message" if an integer is not entered instead of
Enter quantity of DVD: gyfj
Traceback (most recent call last):
File "I:/Python/CourseworkVer3. py", line 203, in <module>
addDvd(catalogu e)
File "I:/Python/CourseworkVer3. py", line 129, in addDvd
dvdQuant = input("Enter quantity of DVD: ")
File "<string>", line 1, in <module>
NameError: name 'gyfj' is not defined

I have the input put into a dictionary so I can multiply with another integer in another function, if I change input to raw_input then when I try and multiply it doesn't recognise the input as an integer

Ihope this isn't too vague and any help would be appreciated
Mar 17 '08 #1
7 16951
Laharl
849 Recognized Expert Contributor
The quickest way to do this is to use raw_input to get a string, then loop over each character in said string and see if it is between '0' and '9'. If you clear the loop without any issues, you have an integer.
Mar 17 '08 #2
elcron
43 New Member
Use try except to handle errors.

Expand|Select|Wrap|Line Numbers
  1. try:
  2.     n = int( raw_input("Enter a number: ") )
  3.     print "n=%s, n squared=%s"%(n, n*n)
  4. except ValueError:
  5.     print "Invalid input."
  6.  
Mar 18 '08 #3
Subsciber123
87 New Member
Expand|Select|Wrap|Line Numbers
  1. n=raw_input("Number: ")
  2. while not n.isdigit(): # this is a builtin method of all str objects
  3.     print "Error: NaN"
  4.     n=raw_input("Number: ")
  5. n=int(n)
  6.  
I believe that this is the simplest possible way to do it. Looping through the string is tedious and processor intensive, even for short strings. Although this is almost guaranteed to be a short string, you should get into the habit of creating readable and efficient code.
Mar 20 '08 #4
marcial
2 New Member
Im also new with python, and what would I have to do if I want the script or the section to restart every time the user inputs wrong information??
Mar 21 '08 #5
bvdet
2,851 Recognized Expert Moderator Specialist
Im also new with python, and what would I have to do if I want the script or the section to restart every time the user inputs wrong information??
Following is an example using a while loop.
Expand|Select|Wrap|Line Numbers
  1. while True:
  2.     s = raw_input("Enter an integer")
  3.     try:
  4.         i = int(s)
  5.         break
  6.     except ValueError:
  7.         print 'Invalid input'
  8.  
  9. print 'Your input of %d is an integer.' % i
Mar 21 '08 #6
marcial
2 New Member
Following is an example using a while loop.
Expand|Select|Wrap|Line Numbers
  1. while True:
  2.     s = raw_input("Enter an integer")
  3.     try:
  4.         i = int(s)
  5.         break
  6.     except ValueError:
  7.         print 'Invalid input'
  8.  
  9. print 'Your input of %d is an integer.' % i
Thanks! I tried to use try-except before without the while loop, and it seems to work very weird, but now with while it works perfect! Thanks!
Mar 21 '08 #7
fatroshi
12 New Member
Works great for me 2 :)
Dec 17 '09 #8

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

Similar topics

4
1542
by: Richard Spooner | last post by:
Hey, I'm very new to python and am trying to do the following. I may get the jargon wrong at times but hopefully you can see what I'm trying to do... I have created a threaded class which sets up a socket and then binds to a port. When I make a new instance I send the port number and I would like the __init__ routine to set up the socket and then attempt to bind it to a port.
27
35950
by: code_wrong | last post by:
Visual Basic (not dot net) what is the best way to check the User has entered an integer into an InputBox? isNumeric() checks for a numeric value .. but does not notify of numbers with decimal places inputBox returns a string so I could check for decimal point??? this seems like overkill The value returned can be asigned into an Integer type and then a Single
2
1373
by: Bob Piton | last post by:
I have just discovered how to do ftp with python, and have a question about using macdef. I can connect to the ftp site, using the .netrc file: machine my.ftpsite.com login myuserid password mypass macdef dload cd maindir
3
1182
by: Kevin Feng | last post by:
I have the following simple html file that is trying to send data to a python script, however, I am getting a weird server error: This is my HTML: <html> <FORM METHOD="POST" ACTION="../cgi-bin/quoteprice2.py"> Ticker 1 <input type="text" name="ticker1" size=10> <br>
7
1311
by: fxlogx | last post by:
here we discuss the most basic concepts about python.
11
2080
by: frankie_85 | last post by:
Hi everyone, I just made a simple code which is part of my assignment but I can't figure it out what's wrong with it. (always give me error messages) What the code basically does is: a function that takes one floating point number x as its argument and returns (the square root of the absolute value of x) plus (5 times x cubed).
21
1568
by: nateastle | last post by:
I have a simple assignment for school but am unsure where to go. The assignment is to read in a text file, split out the words and say which line each word appears in alphabetical order. I have the basic outline of the program done which is: def Xref(filename): try: fp = open(filename, "r") lines = fp.readlines() fp.close()
5
995
by: Gary | last post by:
Hello, I would like to do several checks on a field "First name". I would like to check for the following: No numbers No spaces Two characters or more
1
1528
by: Chaven | last post by:
Hi Ive done some work on a basic python editor, with code folding, syntax highlighting and the idle shell. It also includes a forms editor to quickly build windows forms applications using wxpython widgets. The application still needs some finetuning especially the running of files as it doesnt pass code directly to the interpreter but uses a simple one liner os.startfile(args) which works only with certain files. The compiled file ~ 50 kB. ...
0
9632
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
9471
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
10302
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
10136
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10071
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8958
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
7478
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...
1
4036
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
3
2867
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.