Python中函数间除法运算报TypeError的问题咨询
问题:函数无法直接做除法的 TypeError 解决方法
原始代码
import yfinance as yf import time import math import decimal from decimal import * T = yf.Ticker("T") # 获取年度股息收益率百分比 def DivYield(): div = T.info['dividendYield'] d = Decimal(div) num_1 = d num_2 = 100 M_percent = num_1 * num_2 print(Decimal(int(round(M_percent, 2)))) # 股票的年度收益率百分比 # 获取最新报价 def Last_price(): tickers = ['T'] for ticker in tickers: ticker_yahoo = yf.Ticker(ticker) data = ticker_yahoo.history() last_quote = data['Close'].iloc[-1] Prince = Decimal(last_quote) print(Decimal(int(round(Prince, 2)))) DivYield() Last_price() #price = (Last_price) #DY = (DivYield) payout = DivYield / Last_price print(payout)
错误信息
运行代码时触发如下错误:
payout = DivYield / Last_price ~~~~~~~~~^~~~~~~~~~~~ TypeError: unsupported operand type(s) for /: 'function' and 'function'
需求说明
我期望payout是DivYield和Last_price函数输出的数值相除后保留两位小数的结果(约3.48)。单独调用两个函数能得到预期数值,但作为编程新手,不清楚为何无法完成除法运算,希望得到解决方法。
问题原因
你直接写DivYield / Last_price是在对函数本身做除法,而不是对函数计算出的结果做除法。你的两个函数目前只有print输出动作,没有用return语句返回计算后的数值,所以无法直接参与运算。
修正方案
核心修改点
- 给两个函数添加
return语句,返回计算好的数值(而非只打印) - 调用函数获取返回值后,再执行除法运算
- 对最终结果做两位小数的保留处理
修正后的代码
import yfinance as yf import decimal from decimal import * T = yf.Ticker("T") # 获取年度股息收益率百分比(返回数值) def DivYield(): div = T.info['dividendYield'] d = Decimal(div) M_percent = d * 100 return Decimal(round(M_percent, 2)) # 获取最新报价(返回数值) def Last_price(): ticker_yahoo = yf.Ticker("T") data = ticker_yahoo.history() last_quote = data['Close'].iloc[-1] return Decimal(round(last_quote, 2)) # 调用函数获取计算结果 div_yield = DivYield() last_price = Last_price() # 计算派息率并保留两位小数 payout = div_yield / last_price payout_rounded = Decimal(round(payout, 2)) # 输出结果 print(f"股息收益率: {div_yield}%") print(f"最新股价: {last_price}") print(f"派息率: {payout_rounded}")
额外优化
- 移除了未使用的
time、math库导入 - 简化
Last_price函数的逻辑(无需循环单个股票) - 复用
yf.Ticker("T")实例,提升运行效率 - 用格式化字符串让输出更易读
内容的提问来源于stack exchange,提问作者Caprisun_straw
相关产品推荐
相关产品推荐

