2016-03-06 68 views
-1

我已經寫了大部分的代碼,但我仍然很難找出循環程序的代碼(對於一個函數),直到用戶完成爲止。另外,我無法使用For循環。你如何使用循環功能?

def load(): 
a=input("Name of the stock: ") 
b=int(input("Number of shares Joe bought: ")) 
c=float(input("Stock purchase price: $")) 
d=float(input("Stock selling price: $")) 
e=float(input("Broker commission: ")) 
return a,b,c,d,e 

def calc(b,c,d,e): 
w=b*c 
x=c*(e/100) 
y=b*d 
z=d*(e/100) 
pl=(x+z)-(y-z) 
return w,x,y,z,pl 

def output(a,w,x,y,z,pl): 
print("The Name of the Stock: ",a) 
print("The amount of money Joe paid for the stock: $",format(w,'.2f')) 
print("The amount of commission Joe paid his broker when he bought the stock: $",format(x,'.2f')) 
print("The amount that Jim sold the stock for: $",format(y,'.2f')) 
print("The amount of commission Joe paid his broker when he sold the stock: $",format(z,'.2f')) 
print("The amount of money made or lost: $",format(pl,'.2f')) 

def main(): 
a,b,c,d,e=load() 
w,x,y,z,pl=calc(b,c,d,e) 
output(a,w,x,y,z,pl) 

main() 
+0

對於你想要的,你需要使用'while()'循環。條件應該是一些標誌,當你從用戶設置EOF時,循環也會停止。 –

+0

請指定您希望用戶如何說他已完成。 –

+0

@AvihooMamka我會把這個while()放在def main()或其他地方嗎? – Gangaji

回答

0

爲了讓用戶決定是否要繼續循環,而不是時間任何固定的號碼,詢問用戶:

# in place of the call to main() above, put: 
while input('Proceed? ') == 'y': 
    main() 

所以它不斷,只要用戶輸入「遍歷main() Y」。根據需要,您可以將其更改爲「是」,「是」等。

附註:
1.您應該使用多於1個空格進行縮進。通常4個空格,或至少2個。
2.閱讀if __name__ == "__main__"

0

調用在一個循環的功能是相當簡單的,你無論是在whilefor環包裹和內部調用它。下面的代碼執行10次brookerage函數。我想你可以用這個作爲例子,並根據你的需要定製整個事情。

def brookerage(): 
a,b,c,d,e=load() 
w,x,y,z,pl=calc(b,c,d,e) 
output(a,w,x,y,z,pl) 

def main(): 
for i in range(0,10): 
    brookerage() 

main()