我是一个新的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 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)
答案 0 :(得分:1)
您可以按照评论中的说明获取值raw_input()
(Py3的input()
),也可以将它们作为脚本的args。这是一个小例子,只收集所有-i
args表示in_inches()
,所有-p
参数表示in_pounds()
:
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
答案 1 :(得分:0)
def in_to_cen(num):
return(num * 2.54)
def pds_to_kg(num):
return(num *0.453592)
while True:
print "which conversion?"
print "'1' = pounds to kilograms"
print "'2' = inches to centimeters"
choice = raw_input("? ")
if choice == "1":
num = input("how many pounds? ")
res = pds_to_kg(num)
print str(num) + " is " + str(res) + " Kilograms"
elif choice == "2":
num = input("how many inches? ")
print str(num) + " is " + str(res) + " centimeters."
else:
print "invalid choice"
这就是我认为你想要的。
此程序有一个菜单,询问要进行的转换,然后根据该选项从用户获取数字输入,然后输出正确的转换。
答案 2 :(得分:0)
您可以创建单个函数并在其中执行所有转换,而不是创建许多函数:
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.