简体   繁体   English

如何连续用Python重新运行程序?

[英]How do I continuously re-run a program in Python?

I created a program that calculates how much money is saved after a "percentage off" is applied. 我创建了一个程序,该程序计算应用“折扣百分比”后可以节省多少钱。 The user is able to input the price of the product as well as the percentage off. 用户能够输入产品的价格以及折价百分比。 After the program does the calculation, how do I continuously loop the program so that the user can keep using it without me having to click "run" each time in the console. 程序完成计算后,如何连续循环程序,以便用户可以继续使用它,而不必每次在控制台中单击“运行”。

def percent_off_price():
    price = amount * percent

    amount = float(input('Enter the price of your product: '))
    percent = float(input('Enter the percentage off: '))
    price = amount * percent
    print('You will save $',price,'off!  Your total is: $',amount - price,)

Put the whole code segment in a while loop which runs always but it is the worst thing you would want: 将整个代码段放入一个while循环中,该循环始终运行,但这是您想要的最糟糕的事情:

while True:      
    amount = float(input('Enter the price of your product: '))
    percent = float(input('Enter the percentage off: '))
    price = amount * percent
    print('You will save $',price,'off!  Your total is: $',amount - price,)

You can also put a check to run it for controlled amount. 您还可以检查支票以控制金额运行它。 Hence it would only run if the amount entered is a positive value: 因此,只有在输入的金额为正值时,它才会运行:

flag= True    
while flag:      
    amount = float(input('Enter the price of your product: '))
    if amount <0:
        flag=False
    percent = float(input('Enter the percentage off: '))
    price = amount * percent
    print('You will save $',price,'off!  Your total is: $',amount - price,)

Lastly if you want to run it for a fixed no. 最后,如果要以固定编号运行它。 of times (Let's say 10) you can go for a for loop: 有时(假设10次),您可以进行for循环:

for i in range(10):      
    amount = float(input('Enter the price of your product: '))
    percent = float(input('Enter the percentage off: '))
    price = amount * percent
    print('You will save $',price,'off!  Your total is: $',amount - price,)

You can do: 你可以做:

while True:
  percent_off_price()

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

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