while 循环中的 print() 和 return 语句

print() and return statements in while loops

考虑以下代码:

    MENU = {'sandwich': 10, 'tea': 7, 'pizza': 10, 'soda':3, 'burger': 10}
    
    def restaurant():
        total = 0
        while True:
            order = input('Order: ').lower().strip()
            if not order:
                break
            if order in MENU:
                price = MENU[order]
                total += price
                **return f'{order} is {price}, total is {total}' #will not loop
                print(f'{order} is {price}, total is {total}') #will loop**
            else:
                print(f'Sorry, we are fresh out of {order} today')
        print(f'Your total is {total}')
    
    restaurant()

问题是:

为什么while循环不遍历return而是遍历[=​​13=]?我一直在学习 python 但现在才指出这个场合。

return 将停止函数的执行并且 returns 一些值到调用函数。在您的情况下,字符串 - f'{order} is {price}, total is {total}'

print 只会打印字符串,不会停止函数的执行。