Check if an input is real number?

A forum for general discussion of the Python programming language.

Check if an input is real number?

Postby tdang » Sun Sep 25, 2016 10:46 am

Dear all,
I am a newbie of Python programming. I have tried to write a script to calculate square roots of float numbers. I want to validation input from the keyboard - only float numbers are accepted, otherwise users need to redo. The code is:
Code: Select all
while True:
        x=float(input("Enter a number:"))
    except ValueError:
        print ('Please enter a real number!')
if x<0:
    print '%f is less than 0, it does not have a real square root' % (x)
    while abs(root**2-x)>0.00000000000001:
        print 'Step %d : %f' %(i,root)
    print root

However, when I test it with a string, the running shell stopped and threw an error like that:
Code: Select all
Traceback (most recent call last):
File "/home/tdang/", line 4, in <module>
    x=float(input("Enter a number:"))
  File "<string>", line 0
SyntaxError: unexpected EOF while parsing

I would be really appreciated if anyone can help me clarify this issue.

Thank you.
Last edited by Yoriz on Sun Sep 25, 2016 11:10 am, edited 2 times in total.
Reason: First post lock.
Posts: 1
Joined: Sun Sep 25, 2016 10:40 am

Re: Check if an input is real number?

Postby Yoriz » Sun Sep 25, 2016 11:09 am

In python2 use
Code: Select all
instead of
Code: Select all
Due to the reasons discussed here we will be moving to on October 1 2016
This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.
User avatar
Posts: 1672
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Return to General Discussions

Who is online

Users browsing this forum: Google [Bot] and 3 guests