繁体   English   中英

在 Python 中的函数中使用 input() 作为参数

[英]Use input() as an argument in a function in Python

我创建了这个函数,它返回我正在分析的一些国家的人均 GDP 和人均军事支出,基于特定年份。

def compare(year):
    simple = data.loc[year, :].sort_values(by = "gdp_pc", ascending = False)
    simple = simple.reset_index()
    simple = simple.drop(["gdp_share", "military_exp", "pop", "gdp"], axis = 1)
    simple = simple.round(2)
    simple.columns = ["Countries", "GDP per capita", "Military spending per capita"]
    simple.index = simple.index + 1

    return simple

我已经测试了该功能并且它工作正常。 但是,我想让它更加用户友好,并让用户输入年份(函数的参数)。 我该怎么做呢?

定义一个包装函数; compare做它的事情(实际的比较),让另一个函数负责调用input并将响应传递给compare

def do_comparison():
    year = int(input("Enter a year to compare against: "))
    return compare(year)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM