程序如何在python中的两个函数之间进行选择? [英] How can the program choose between two function in python?

查看:53
本文介绍了程序如何在python中的两个函数之间进行选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python 3.2程序,该程序可以计算在未来任何时间段内进行的投资的价值,它可能适用于单利和复利.问题是我定义了两个函数"main()"和"main2()",第一个用于简单,第二个用于复利.现在,我想做的是,在给定用户输入的情况下,程序在运行main()或main2()之间进行选择.有关如何执行此操作的任何想法?

I've got a Python 3.2 program that computes the value of an investment carried any amount of time periods into the future, it may work with both simple and compound interest. The thing is that I've got two functions defined, "main()" and "main2()", the first is for simple and the second is for compound interest. Now what I want to do is that given some input from the user the program chooses between running main() or main2(). Any ideas on how to do this?

推荐答案

首先,给函数命名更好的名称.然后使用映射:

First of all, give your functions better names. Then use a mapping:

def calculate_compound(arg1, arg2):
    # calculate compound interest

def calculate_simple(arg1, arg2):
    # calculate simple interest

functions = {
    'compound': calculate_compound,
    'simple':   calculate_simple
}

interest = functions[userchoice](inputvalue1, inputvalue2)

由于Python函数是一等公民,您可以将它们存储在python字典中,使用键进行查找,然后调用它们.

Because Python functions are first-class citizens you can store them in a python dictionary, use a key to look them up, then call them.

这篇关于程序如何在python中的两个函数之间进行选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆