Python简单转换器
我是一个新的python程序员,目前正在用python开发一个非常简单的转换器。我现在有这个,但我想让它可以随时更改'n'Python简单转换器,python,python-2.7,Python,Python 2.7,我是一个新的python程序员,目前正在用python开发一个非常简单的转换器。我现在有这个,但我想让它可以随时更改'n' #inches to centimeters def in_inches(n): resulti = n * 100 return resulti n = 10 resulti = in_inches(n) print "In %d inches we have %d centimeters" % (n, resulti) #pounds to kilo
#inches to centimeters
def in_inches(n):
resulti = n * 100
return resulti
n = 10
resulti = in_inches(n)
print "In %d inches we have %d centimeters" % (n, resulti)
#pounds to kilograms
def in_pounds(x):
resultp = x * 0.453592
return resultp
x = 10.0
resultp = in_pounds(x)
print "In %d pounds we have %d kilograms." % (x, resultp)
这就是我认为你想要的
此程序有一个菜单,询问要进行哪种转换,然后根据该选择从用户处获取数字输入,然后输出正确的转换。您可以创建一个函数,并在其中执行所有转换,而不是执行多个函数:
def convert(n, fromto):
if fromto == "in_cm":
print "In %d inches we have %d centimeters" %(n, n*100)
if fromto == "kg_pound":
print "In %d pounds we have %d kilograms." %(n, n*0.453592)
convert(2, "in_cm")
convert(5, "kg_pound")
输出:
In 2 inches we have 200 centimeters
In 5 pounds we have 2 kilograms.
您可以按照注释中提到的方式将值获取为
raw\u input()
(input()
,对于Py3),也可以将它们获取为脚本的参数。下面是一个小示例,它只收集了所有-i
参数,表示以英寸为单位()
,以及所有-p
参数,表示以磅为单位()
:
然后,只需使用所需的任何参数调用脚本:
$ python myconverter.py -p 7 -i 42 -p 10 -p 12
In 42.0 inches we have 107.52 centimeters
In 7.0 pounds we have 3.175144 kilos
In 10.0 pounds we have 4.53592 kilos
In 12.0 pounds we have 5.443104 kilos
您可以使用
input
让用户设置n
的值。。。对于Python2,我建议raw\u input
@JulienBernu Actualinput()
是错误的函数。他需要raw\u input()
@leaf同意,很明显OP使用的是Py2.X,这显然不适用于Py3。input()
在Py2中通常被认为是有害的int(原始输入(…)
被认为更安全,或者更灵活地ast.literal\u eval(原始输入(…)
。
from __future__ import print_function # Really should start moving to Py3
#inches to centimeters
def in_inches(n):
resulti = n * 2.56
return resulti
#pounds to kilograms
def in_pounds(x):
resultp = x * 0.453592
return resultp
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('-i', '--inches', default=[], type=float, action='append')
parser.add_argument('-p', '--pounds', default=[], type=float, action='append')
args = parser.parse_args()
for n in args.inches:
print("In {} inches we have {} centimeters".format(n, in_inches(n)))
for x in args.pounds:
print("In {} inches we have {} centimeters".format(x, in_pounds(x)))
$ python myconverter.py -p 7 -i 42 -p 10 -p 12
In 42.0 inches we have 107.52 centimeters
In 7.0 pounds we have 3.175144 kilos
In 10.0 pounds we have 4.53592 kilos
In 12.0 pounds we have 5.443104 kilos