简体   繁体   English

你如何为函数使用循环?

[英]How do you use a loop for a function?

I have written most of the codes already, but I am still having a hard time figuring out the code to loop the program (for a function) as many times the user desires until the user is done.我已经编写了大部分代码,但是我仍然很难找出代码来循环程序(对于函数),直到用户完成为止。 Also, I am unable to use a For loop.另外,我无法使用 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()

Calling a function in a loop is fairly simple, you wrap in either in a while or a for loop and call it inside.在循环中调用函数相当简单,您可以将其包装在whilefor循环中并在内部调用它。 The below code executes the brookerage function 10 times.下面的代码执行了 10 次brookerage I suppose you can use this as an example and customize the entire thing for your needs.我想您可以以此为例,并根据您的需要自定义整个内容。

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()

To let the user decide if they want to keep looping and not any fixed number of times, ask the user:要让用户决定是否要继续循环而不是任何固定次数,请询问用户:

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

So it keeps looping over main() as long as the user enters 'y'.因此,只要用户输入“y”,它就会一直在main()循环。 You can change it to 'yes', 'Yes', etc. as needed.您可以根据需要将其更改为“是”、“是”等。

Side note:边注:
1. You should use more than 1 space for indent. 1. 缩进应该使用 1 个以上的空格。 Typically 4 spaces, or at least 2.通常为 4 个空格,或至少 2 个。
2. read up on if __name__ == "__main__" . 2. if __name__ == "__main__"阅读if __name__ == "__main__"

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

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