是我,你友好的 Python 菜鸟!
我正在研究这个程序,我试图弄清楚如果数字超过某个阈值或者如果用户输入数字以外的任何内容以循环并重试,如何让程序停止。
这是我目前所拥有的:
def ticket_a_sales_calculation(section_a_ticket_purchased):
section_a_sales = section_a_ticket_purchased * 20
return section_a_sales
def ticket_b_sales_calculation(section_b_ticket_purchased):
section_b_sales = section_b_ticket_purchased * 15
return section_b_sales
def ticket_c_sales_calculation(section_c_ticket_purchased):
section_c_sales = section_c_ticket_purchased * 10
return section_c_sales
def total_sales_calculation(ticket_a_sale, ticket_b_sale, ticket_c_sale):
total_sales = ticket_a_sale + ticket_b_sale + ticket_c_sale
return total_sales
def sales_report(ticket_a_sales, ticket_b_sales, ticket_c_sales, sales_totals):
print("Ticket A Sales: $" + format(ticket_a_sales, ",.2f"))
print("Ticket B Sales: $" + format(ticket_b_sales, ",.2f"))
print("Ticket C Sales: $" + format(ticket_c_sales, ",.2f"))
print("Total Sales: $" + format(sales_totals, ",.2f"))
def main():
ticket_a_purchased = int(input("Please enter the amount of tickets sold for section A: "))
if ticket_a_purchased > 300:
print("Number exceeds amount of available seats")
ticket_b_purchased = int(input("Please enter the amount of tickets sold for section B: "))
if ticket_b_purchased > 500:
print("Number exceeds amount of available seats")
ticket_c_purchased = int(input("Please enter the amount of tickets sold for section C: "))
if ticket_c_purchased > 200:
print("Number exceeds amount of available seats")
ticket_a_sales = ticket_a_sales_calculation(ticket_a_purchased)
ticket_b_sales = ticket_b_sales_calculation(ticket_b_purchased)
ticket_c_sales = ticket_c_sales_calculation(ticket_c_purchased)
total_sales = total_sales_calculation(ticket_a_sales,ticket_b_sales,ticket_c_sales)
sales_report(ticket_a_sales, ticket_b_sales, ticket_c_sales, total_sales)
main()
main()
中的 if 语句正在打印我想要的内容,但我想要做的是让程序在特定条件下停止。我知道 while
或 for
循环会有所帮助,但我不知道如何设置它。
接下来我最终尝试的是:
seats_a = True
while True:
if seats_a > 300:
print("Number exceeds amount of available seats")
elif seats_a < 300:
continue
那根本行不通。
此时我不知所措。谁能把我推向正确的方向?我觉得 if
语句不是正确的方法。我觉得使用 while
循环会更好,并且会给出我正在寻找的结果。
天哪,我希望这是有道理的。
谢谢大家!
最佳答案
这个习语应该适用于这种情况:
while True:
ticket_a_input = input("Please enter the amount of tickets sold for section A: ")
if not ticket_a_input.isdigit():
print("Ticket amount must be a number")
continue
if int(ticket_a_input) > 300:
print("Number exceeds amount of available seats")
continue
ticket_a_purchased = int(ticket_a_input)
break
我们在这里所做的是使用 while True
无限、无条件地循环。然后,根据用户输入的内容,
- 如果用户输入的不是数字,那么我们会打印一条错误消息并使用
continue
跳回到循环的开头 - 否则,如果用户输入的数字大于 300,则打印不同的错误消息并重新启动循环
- 如果用户的输入是有效的并且没有命中其中任何一个,则将
ticket_a_purchased
和break
设置为退出循环。
这种类型的习语适用于大多数“条件输入”,其中输入可能有效也可能无效,你想一直询问直到它有效,但它很少是其他场景的最佳解决方案.在合理的情况下,您希望尝试使用一个可以自行满足的实际条件的 while
循环。如果这样做,您需要非常小心,以某种方式覆盖循环中的每条可能路径,否则您可能会发现自己处于牢不可破的循环中。
关于python - 我应该使用 if 语句还是循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64456160/