【问题标题】:How do you use a loop for a function?如何为函数使用循环?
【发布时间】:2016-03-06 10:02:49
【问题描述】:

我已经编写了大部分代码,但是在用户完成之前,我仍然很难弄清楚循环程序(对于函数)的次数,直到用户完成为止。另外,我无法使用 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()

【问题讨论】:

  • 对于您想要的,您需要使用while() 循环。条件应该是一些标志,当您从用户那里设置 EOF 时,循环也会停止。
  • 请指定您希望用户如何说他已完成。
  • @AvihooMamka 我会将 while() 放在 def main() 中还是其他地方?
  • 无论您在哪里包装需要多次运行的函数。
  • 知道了!感谢您的帮助!

标签: python loops python-3.x input


【解决方案1】:

要让用户决定是否要继续循环而不是任何固定次数,请询问用户:

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

所以只要用户输入'y',它就会不断循环main()。您可以根据需要将其更改为“是”、“是”等。

旁注:
1. 缩进应使用 1 个以上的空格。通常为 4 个空格,或至少 2 个。
2. 阅读if __name__ == "__main__"。

【讨论】:

    【解决方案2】:

    在循环中调用函数相当简单,您可以将其包裹在while 或for 循环中并在其中调用它。下面的代码执行了 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-03
      • 2021-04-20
      • 2019-06-11
      • 2020-10-11
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多