【问题标题】:print() and return statements in while loops [closed]while 循环中的 print() 和 return 语句[关闭]
【发布时间】:2024-01-01 05:08:01
【问题描述】:

考虑下面的代码:

    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,而是循环通过print?我一直在学习python,但现在才指出这个场合。

【问题讨论】:

  • "return" 结束函数并返回一个值,"print" 只是将值打印到控制台上
  • printreturn 没有任何共同之处(尽管 REPL 有打印表达式值的做法)。
  • 你觉得return应该怎么做?

标签: python loops while-loop printing return


【解决方案1】:

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

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

【讨论】:

    最近更新 更多