[英]Calling an output from a function from a different file?
這是一個非常基本的問題。
我有一個程序,可以根據用戶輸入的天數計算水果(蘋果+香蕉)的總數。 蘋果的產量和總水果計數在fruit.py中計算:
from bananas import Bp
day_count = int(input("How many days have passed?" ))
apple_production = day_count * 100
fruit_total = apple_production + banana_production
print("Total amount of fruit is", fruit_total)
香蕉產量是在另一個文件bananas.py中計算的,並定義為一個函數:
def Bp(day_count):
banana_production = day_count * 200
return banana_production
所以我的問題是,當我嘗試運行bananas.py時,出現錯誤“未定義名稱'banana_production'”。
顯然,我在這里錯過了重要的一步。 我如何從bananas.py調用banana_production的輸出值以在fruit.py中使用?
順便說一句,我意識到我可以將兩者合並到一個文件中,但是這個問題的重點是找出如何用這種方法來做。
我認為您想讓fruit.py說:
from bananas import Bp
day_count = int(input("How many days have passed?" ))
apple_production = day_count * 100
fruit_total = apple_production + Bp(day_count) # see how I'm calling the function declared in bananas.py
print("Total amount of fruit is", fruit_total)
(如果您已經向我們展示了bananas.py的全部內容,則沒有什么可以“運行”的。它只是一個函數聲明。按照所述方式運行bananas.py不會給出您所描述的錯誤消息。也許您的意思是“當我運行fruit.py”?)
您收到消息banana_production未定義,因為您尚未在fruit.py中的任何地方定義它。 盡管變量是在bananas.py中定義的,但是您必須執行以下操作才能實現所需的功能:
因此,您要做的就是添加以下行:
banana_production = Bp(day_count)
計算出apple_production之后
bananas.py :(不變):
def Bp(day_count):
banana_production = day_count * 200
return banana_production
fruit.py:
from bananas import Bp
day_count = int(input("How many days have passed?" ))
apple_production = day_count * 100
banana_production = Bp(day_count) # Add this line
fruit_total = apple_production + banana_production
print("Total amount of fruit is", fruit_total)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.