如何在python中重复一段代码一定次数

时间:2014-03-15 09:48:43

标签: python loops repeat

基本上我想做的就是写一段关于泡茶的代码(学校作业)

所以基本上这里是我的代码

print ("Making A Cup Of Tea")
a=input("How many for Tea")
print ("there are",a,"People for tea")
b=input ("Would you like Sugar? YES/NO")
if (b) == ("YES"):
    c=input("How many sugars?")
elif (b) == ("NO"):
    print ("Okay No sugar")
e=input("How Much Milk Would You Like? SMALL/MEDIUM/LARGE")
print ("YOUR ORDER IS BEING PROCESSED PLEASE WAIT...")
if (a) == ("1"):
    print("There is",a,"Order with",c,"sugar(s),with",e,"amount of milk")
elif (a) >= ("2"):
    print("There is",a,"Orders with",c,"sugar(s),with",e,"amount of milk")

但我想要它做的不是必须做同样的订单,我怎么能适应它,以便在这种情况下(a)将在底部打印茶的人数。

所以例如:

有3个人喝茶, 所以我希望程序重复3次,然后在每个订单的底部打印

2 个答案:

答案 0 :(得分:2)

for x in range(n):
    do_something()

答案 1 :(得分:0)

也许这可以帮到你:

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')

前面的代码将生成类似于:

的输出
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