如何在不运行连续循环的情况下在循环时运行某些python程序

时间:2019-10-24 13:06:36

标签: python while-loop

我正在尝试获取一个程序以询问费用 然后要求保证金。 我希望能够使用不同的保证金来重复。我尝试了不同的方法,但是都会导致连续循环。

几年前,我有这个程序,它可以正常工作,我记得它很简单,但现在无法获取。

我不记得我尝试过的所有内容。我尝试过一段时间,如果我在这里尝试过语句,但是由于我不知道如何格式化,所以它不会让我过帐。尝试了其他while语句,如果else语句继续,则中断。

cost = input('Enter cost: ')
cost = float(cost)
margin = input('Enter margin: ')
margin= float(margin)
while margin != 0:
    print('List equals', cost/margin)

期望它询问成本和利润。然后将费用除以保证金,给出答案并重复进行,直到我输入止损或保证金不等于一定数额为止。

2 个答案:

答案 0 :(得分:4)

您当前格式的脚本读取输入并将其设置为costmargin的浮点数,然后如果margin不是0,则进入循环。因此,假设您为margin设置了一些非零值,则进入循环。但是一旦进入循环,就永远不会更改margin的值,因此循环的条件永远保持为True

相反,您可以运行无限循环并在循环的每次迭代中继续读取边距。如果margin的值非0,则将打印结果。如果margin的值为0,则循环将中断。

cost = float(input('Enter cost: '))
while True:
    margin = float(input('Enter margin: '))
    if margin:
        print('List equals', cost/margin)
    else:
        break

输出

Enter cost: 10
Enter margin: 2
List equals 5.0
Enter margin: 3
List equals 3.3333333333333335
Enter margin: 0

Process finished with exit code 0

答案 1 :(得分:1)

您可以使用以下代码段来实现

while True :
    cost = input('Enter cost: ')
    cost = float(cost)
    margin = input('Enter margin: ')
    margin= float(margin)
    print(margin)
    if margin != 0 :   # or what ever value you want it to be
        print('List equals', cost/margin)
        break
    else :
        continue

结果:

Enter cost: 0
Enter margin: 10
10.0
Enter cost: 20
Enter margin: 20
20.0
List equals 1.0
-----------------
相关问题