Validating user input is a float ?

This is the place for queries that don't fit in any of the other categories.

Validating user input is a float ?

Postby nytman » Sat Jul 27, 2013 8:55 am

dear list,
I am new to python and trying to write a simple program in which i asked user to input a salary, what problem i am facing is i want user to only input integer or float data types when ever user input anything other than integer or float i will ask user to again input the salary, this can be done by using "try and except" method but i want to do this without using "try and except" method , my code by using "try and except" method is :
Code: Select all
b = 0
while b == False:
    try:
        a = float(raw_input("Give me a number"))
        b = isinstance(a, float)
       
    except ValueError:
        print "Could you at least give me an actual number?"
   
print "salary is: ", a


this is working fine as do what i exactly i want, but when i tried to do this with using "try and except" i got failed , need some help.
Thanking you in advance, Waiting for your reply
warm regards
Last edited by Yoriz on Sat Jul 27, 2013 10:38 am, edited 1 time in total.
Reason: changed title
nytman
 
Posts: 4
Joined: Sat Jul 27, 2013 8:44 am

Re: isfloat()

Postby Yoriz » Sat Jul 27, 2013 10:02 am

What is wrong with try and accept? try and accept is the python way of doing things like this

nytman wrote:this is working fine as do what i exactly i want, but when i tried to do this with using "try and except" i got failed
This doesn't make sense you seaid it works fine and failed at at the same time.

Use while True and then break out of the loop
Code: Select all
while True:
    try:
        a = float(raw_input("Give me a number"))
        break

    except ValueError:
        print "Could you at least give me an actual number?"

print "salary is: ", a
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 571
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: Validating user input is a float ?

Postby nytman » Sat Jul 27, 2013 10:43 am

Sorry sir, there was my typing mistake, I mean to say it works fine with "try and except" method , but when I tried to do the same without using "try and except" I got failed.
So I was here to find another way to solve my problem.
I am new to python so please forgive me if I asked anything irrelevant.
Waiting for your reply.
Warm regards
nytman
 
Posts: 4
Joined: Sat Jul 27, 2013 8:44 am

Re: Validating user input is a float ?

Postby stranac » Sat Jul 27, 2013 11:08 am

The try/except method is the correct way to do it.

If you have a good reason for doing the checking for yourself(such as learning or whatever), you'll need to check that the input matches the format of what you consider a valid float(hard to say exactly what you want).
You could use python's built-in string handling capabilities for this, or use something like the re module.

Anyway, you'll need to be more specific about what you consider a float, and post some code you've tried.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 908
Joined: Thu Feb 07, 2013 3:42 pm

Re: Validating user input is a float ?

Postby Yoriz » Sat Jul 27, 2013 11:16 am

This is from the python docs glossary
EAFP
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

LBYL

Look before you leap. This coding style explicitly tests for pre-conditions before making calls or lookups. This style contrasts with the EAFP approach and is characterized by the presence of many if statements.

In a multi-threaded environment, the LBYL approach can risk introducing a race condition between “the looking” and “the leaping”. For example, the code, if key in mapping: return mapping[key] can fail if another thread removes key from mapping after the test, but before the lookup. This issue can be solved with locks or by using the EAFP approach.


Here is a video explaination [YouTube]Permission or Forgiveness?
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 571
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: Validating user input is a float ?

Postby nytman » Sat Jul 27, 2013 6:22 pm

#Anyway, you'll need to be more specific about what you consider a float, and post some code you've tried.


Code: Select all
# get original input
n1 = raw_input("enter your name: ")

while not (n1.isalpha()):
# check of n1 is a digit, if not get valid entry
    n1 = raw_input ("enter a valid name: ")

num1 = str(n1)



n2 = raw_input("enter number: ")
while not (n2.isdigit()):
    n2 = raw_input("enter a valid number: ")

num2 = int(n2)


this is how i replace "try and except" method for alphabet(name) and integer(number), by using isdigit() and isalpha() , by this user can only enter alphabet when i asked him to enter name, and user can only enter integer when i asked him to enter number, so i can bared the rough entries entered by user, but i was unable to find some similar solution in case of float, if i want user to input only float value and bared the other random input used by user, the only solution for this i have is "try and except" method and my code for "try and except" is :

Code: Select all
b = 0
while b == False:
    try:
        a = float(raw_input("Give me a number"))
        b = isinstance(a, float)
       
    except ValueError:
        print "Could you at least give me an actual number?"
   
print "salary is: ", a


this code is working fine but i am looking for some other method to do the same for float entries.
As i am new to python and also new in programming, please forgive me if i asked something irrelevant.
nytman
 
Posts: 4
Joined: Sat Jul 27, 2013 8:44 am

Re: Validating user input is a float ?

Postby metulburr » Sat Jul 27, 2013 7:47 pm

Code: Select all
    b = 0
    while b == False:
        try:
            a = float(raw_input("Give me a number"))
            b = isinstance(a, float)
           
        except ValueError:
            print "Could you at least give me an actual number?"
       
    print "salary is: ", a




this code is working fine but i am looking for some other method to do the same for float entries

Yoriz already gave it to you in his first post. I dont see what you have gained in this code snippet , it is very C-like, does not get rid of try/except, and complicates something simple.
New Users, Read This
version Python 3.3.2 and 2.7.5, tkinter 8.5, pyqt 4.8.4, pygame 1.9.2 pre
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
User avatar
metulburr
 
Posts: 1122
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests