【问题标题】:Why is my print function printing the () and the "" along with the statement?为什么我的打印函数打印 () 和 "" 以及语句?
【发布时间】:2016-03-31 23:56:03
【问题描述】:

这是我为绝对初学者准备的 Python 编程挑战的代码

    food = input("What is your favorite entree? ")

    dessert = input("What is your favorite dessert? ")

    print("\nI am going to assume that your favorite meal is" , food +   dessert)

代替打印

I am going to assume that your favorite meal is

正在打印

('\nI am going to assume that your favorite meal is', 'steakcookies')

我需要改变什么?

【问题讨论】:

  • print 不是函数,您不要在参数周围加上括号。所以括号正在创建一个列表,它正在打印列表。
  • @Barmar:一个元组,而不是一个列表。
  • 通常我们会看到相反的问题——人们试图在 Python 3 上使用 Python 2 语法,却被 SyntaxError 弄糊涂了。
  • 在 python 2.7 中,当你使用 print(some, text, here) 时,它会打印一个以 some, text 和 here 作为元组成员的元组。您可以通过不使用括号来解决此问题,因此:

标签: python python-2.7 function printing


【解决方案1】:

您将其视为 Python 3 的 print() 函数。当您在 Python 2 中执行此操作时,它会打印您提供给它的对象,即 tuple。在 Python 3 中,这些括号将描述函数调用,每个包含的对象都是传递给函数的参数。

如果您希望它按照您期望的方式运行,请在代码顶部导入 print() 函数:

from __future__ import print_function

从那时起,在该程序中,print 将引用函数,而不是语句。

【讨论】:

    【解决方案2】:

    你需要去掉括号:

    print "\nI am going to assume that your favorite meal is" , food +   dessert
    

    在 Python2 中,print 是一个语句,而不是一个函数。当您包含括号时,print 将参数视为元组的一部分。您还应该使用raw_input(),而不是input()。或者,将from __future__ import print_function 放在文件的开头。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-18
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      相关资源
      最近更新 更多