带有While循环的If语句,尝试使其从一个If转到另一个If,直到到达末尾

2024-09-26 18:19:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望它能够这样,如果条件不再是真的,它会在条件中不断移动,最终达到价格过高而客户离开的条件

yes_no = input("")
if yes_no == '2':
    trade = True
    while trade:
        if currentPrice < maxPrice - 40 and currentPrice < maxPrice - 16:
            priceIncrease = random.randint(8, 25)
            print(currentName,": ummm, sure i'll raise the price by ",priceIncrease)
            currentPrice += priceIncrease
            #this should always be the very last thing
            earnedMoney += currentPrice #

            trade = False

        elif currentPrice <= maxPrice - 16:                            #Change the '0.9' in future days to make it harder
            priceIncrease = random.randint(8, 25)
            print(currentName,": ughh, i'm not sure.... fine, i'll raise the price by",priceIncrease)

            #this should always be the very last thing
            earnedMoney += currentPrice #

            trade = False 

        elif currentPrice > maxPrice - 16 :
            print("Are you serious?? i know how much this product is worth \n")

            #this should always be the very last thing
            earnedMoney += currentPrice #
            trade = False

        else:
            print("this should never be printed")
            break

现在如果你运行这个程序,它只会继续到下一个循环,因为

trade = False

如果我删除它,它只会继续打印最初到达的条件

请帮忙这是学校的一个项目,我好像做不好


Tags: thefalsebethis条件alwaysverylast
1条回答
网友
1楼 · 发布于 2024-09-26 18:19:19

听起来你好像在说这种类型的循环:

trade = True
while trade:
    print "In the loop"
    trade = False
print "Past the loop"

从不打印"In the loop"。对吗

另外,有一个可运行的示例,例如currentPricemaxPrice集也是很有帮助的

例如,我认为这是预期的:

trade = True
currentPrice = 10
maxPrice = 18
while trade:
    if currentPrice < maxPrice - 40 and currentPrice < maxPrice - 16:
        print "First branch"
        trade = False

    elif currentPrice <= maxPrice - 16:
        print "Second branch"
        trade = False

    elif currentPrice > maxPrice - 16 :
        print "Third branch"
        trade = False

    else:
        print("this should never be printed")
        break
print "After loop"

(另外,if的第一个分支有一些额外的逻辑…currentPrice < maxPrice - 40currentPrice < maxPrice - 16实际上并不都是必需的。)

相关问题 更多 >

    热门问题