在Python中使用三元布尔函数进行数学运算。

问题描述 投票:-1回答:1

我写了这个小脚本来计算狗年。前两个狗年是10.5人年,之后的所有其他年份都是4年。

human_age = int(input("Enter the human age to convert it to doggy years: "))
    valid = (human_age <=2)
    def convert_to_dog_years(human_age):
        if valid:
            dog_years = human_age * 10.5
            print('Dog age is:', int(dog_years))
        elif not valid:
            dog_years = ((((human_age - 2) * 4) + 21))
            print('Dog age is:', int(dog_years))
    convert_to_dog_years(human_age)

我想的更多的是这样的:我想指定数学运算,给他们两个名字,一个是0-2的数字,另一个是2以上的数字,然后我想用一个布尔值来决定我想应用哪个数学过程。

这在python中可以实现吗?

0-2    = dog_years = human_age * 10.5
>=2    = dog_years = ((((human_age - 2) * 4) + 21))

human_age = int(input("Enter the human age to convert it to doggy years: "))
valid = (human_age <=2)
def convert_to_dog_years(human_age):
    if valid 0-2 else 2&up
        print('Dog age is:', int(dog_years))
convert_to_dog_years(human_age)
python python-3.x python-2.7 boolean-logic conditional-operator
1个回答
3
投票

虽然,这个问题没有清楚地表达出来,但似乎你正在寻找存储函数并有条件地调用这些函数的方法。

好消息是,在python中,函数是一级对象。

所以,你可以这样做 -

>>> handlers={
...  'valid':lambda human_age:human_age * 10.5,
...  'invalid': lambda human_age:((((human_age - 2) * 4) + 21))}
>>> handler_key = 'valid' if human_age <=2 else 'invalid'
>>> human_age=3 #In your case, take input here
>>> print(handlers[handler_key](human_age)) #call handler
25

为了进一步回应OPs的评论,lambda's在任何情况下都不是必不可少的。以下是同样的代码,但有简单的函数

>>> def invalid_handler(human_age): return ((((human_age - 2) * 4) + 21))
... 
>>> def valid_handler(human_age): return human_age * 10.5
... 
>>> handlers = {
...  'valid': valid_handler,
...  'invalid': invalid_handler}
>>> 
>>> print(handlers[handler_key](human_age))
25
>>> human_age=1
>>> print(handlers[handler_key](human_age))
17

我也想借此机会对python和几乎所有的现代编程语言做一个简短的抨击。

在现代编程语言中,为什么同样的事情有这么多方法?

Python禅宗》第13期指出------。

应该有一种 -- -- 最好只有一种 -- -- 明显的方法来做。

然而,有多种方法可以达到同样的结果。我真的希望现代的编程语言能够扼杀增加尽可能多的功能的诱惑,而专注于做好最重要的工作--速度、工具、更好的版本、框架。

我来自'C'背景,我相信它是迄今为止最好的编程语言。

© www.soinside.com 2019 - 2024. All rights reserved.