【发布时间】:2020-08-15 02:14:57
【问题描述】:
我写了这个小脚本来计算狗年。前两个狗年是人类年的 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)
【问题讨论】:
-
编辑以将
human_age作为一行:human_age = int(input(....),为什么0-2有更好的变量选择?第一选择有什么问题,在if语句的帮助下,这两种情况都使用布尔值。
标签: python python-3.x python-2.7 boolean-logic conditional-operator