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
x=0.0
while True:
    try:
        x=float(input("Enter a number:"))
    except ValueError:
        print ('Please enter a real number!')
        continue
    else:
        break
if x<0:
    print '%f is less than 0, it does not have a real square root' % (x)
else:
    root=x/2
    i=1
    while abs(root**2-x)>0.00000000000001:
        root=0.5*(root+x/root)
        print 'Step %d : %f' %(i,root)
        i+=1
    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/sqrt.py", 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.
tdang
 
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
raw_input
instead of
Code: Select all
input
Due to the reasons discussed here we will be moving to python-forum.io/ 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
Yoriz
 
Posts: 1672
Joined: Fri Feb 08, 2013 1:35 am
Location: UK


Return to General Discussions

Who is online

Users browsing this forum: No registered users and 2 guests