Inputing floats, integers, or equations in raw_input to define a variable

我只是一个虾纸丫 提交于 2019-12-08 04:36:28

You'll need to either parse the string yourself (the ast module would probably be useful), or use eval:

>>> s = '6*pi'
>>> eval(s,{'__builtins__': None, 'pi': np.pi})
18.84955592153876

Note that there are some nasty things that users can do with eval. My solution protects you from most of them, but not all -- pre-checking the string to make sure that there aren't any __ will make it even safer (that eliminates all of the vulnerabilities that I know of, but there could be others)

I would like the user to either enter a number, or something like 6 * np.pi (6Pi).

To implement this you need to do two things :

  • First,check whether your input is an int or float

    This is simple. You can check for this by multiple isinstance checks

  • If not, then you need to execute the input as a command and save the output in a variable

    Once you are sure it is a command, then you can use the exec or eval command to execute the input and store the output in a variable.

    Example : exec("""v = 6*2""") or v = eval("6*2") both of which assign 12 to v


I'm using Python 2.7 and Ecplise workspace. This source code is working fine for me, by-using raw_input.

import time

startTime = time.clock()
print "{0:*^80}".format(" Begins ")

name = raw_input('Please give the name : ')
print "Name is : ".ljust(40, '.'), name
print "Length of name : ".ljust(40, '.'), len(name)

print
radius = float(raw_input('Please enter the radius of circle : '))
print "Radius is : ".ljust(40, '.'),radius
diameter = float(2 * radius)
print "Diameter of circle is : ".ljust(40, '.'), diameter

print "\n{0:*^80}".format(" End ")

print "\nElapsed time : ", (time.clock() - startTime)*1000000, "microseconds"

Here, input :
name : "Sir! Guido von Rossum" and
radius : 1.1

Output :

************************************ Begins ************************************
Please give the name : Sir! Guido von Rossum
Name is : .............................. Sir! Guido von Rossum
Length of name : ....................... 21

Please enter the radius of circle : 1.1
Radius is : ............................ 1.1
Diameter of circle is : ................ 2.2

************************************* End **************************************

Elapsed time :  3593748.49903 microseconds

Thought, might be it helps you or someone else.
Thanks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!