Python简单控件

2024-04-26 23:50:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个新的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)

Tags: toinreturndefhave程序员weprint
3条回答

您可以创建单个函数并在其中执行所有转换,而不是生成许多函数:

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")

输出:

^{pr2}$

您可以获得注释中提到的raw_input()(Py3为input()),也可以将它们作为脚本的参数。下面是一个小例子,它只收集所有的-i参数来表示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)))

然后,您只需使用您想要的任何参数调用脚本:

^{pr2}$
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"

我想这就是你想要的。在

这个程序有一个菜单,询问要进行哪种转换,然后根据这个选择从用户那里获得一个数字输入,然后输出正确的转换。在

相关问题 更多 >