How to Repeat a piece of code a certain amount of times in python

扶醉桌前 提交于 2019-12-02 11:12:46

Maybe this can help you:

print ("Making A Cup Of Tea")
num_orders = int(input("How many for Tea? "))
print ("there are", num_orders, "People for tea")
orders = []
for i in range(num_orders):
    b = input ("Person %i, Would you like Sugar? YES/NO " % (i + 1))
    sugar = None
    if b in ("YES", "Y", "y", "yes"):
        sugar = input("How many sugars? ")
    else:
        print ("Okay No sugar")

    milk = input("How Much Milk Would You Like? SMALL/MEDIUM/LARGE ")

    print ("Order is being processed, next order:\n")
    orders.append({'sugar': sugar, 'milk': milk })

print('The orders has been processed with these data:')
for i in range(num_orders):
    order = orders[i]
    print (' - Person', i + 1, 'wants tea', ('with %i' % int(order['sugar']) if order['sugar'] else 'without'), 'sugar and ', order['milk'], 'milk')

The previous code will generate an output similar to:

Making A Cup Of Tea
How many for Tea? 3
there are 3 People for tea
Person 1, Would you like Sugar? YES/NO y
How many sugars? 1
How Much Milk Would You Like? SMALL/MEDIUM/LARGE small
Order is being processed, next order:

Person 2, Would you like Sugar? YES/NO n
Okay No sugar
How Much Milk Would You Like? SMALL/MEDIUM/LARGE large
Order is being processed, next order:

Person 3, Would you like Sugar? YES/NO y
How many sugars? 2
How Much Milk Would You Like? SMALL/MEDIUM/LARGE small
Order is being processed, next order:

The orders has been processed with these data:
 - Person 1 wants tea with 1 sugar and small milk
 - Person 2 wants tea without sugar and large milk
 - Person 3 wants tea with 2 sugar and small milk
for x in range(n):
    do_something()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!