Python +;的操作数类型不受支持:';功能';和';str';

Python +;的操作数类型不受支持:';功能';和';str';,python,Python,请帮帮我,我不明白为什么这不起作用,我已经尝试了我想到的一切:) 似乎问题出在第19行的打印部分 def name(): name = str(input("What is your name")) print("Hello " + name + " Welcome to the hotel!") return name def bed_category(): category = str(input("

请帮帮我,我不明白为什么这不起作用,我已经尝试了我想到的一切:) 似乎问题出在第19行的打印部分

def name():
  name = str(input("What is your name"))
  print("Hello " + name + " Welcome to the hotel!")
  return name
  
def bed_category():
  category = str(input("What category of room would you like? (single,twin,double)"))
  return category
  
def number_of_nights():
  nights = int(input("How many nights will you be staying?"))
  return nights


def total_cost():
  cost = 40 * nights
  if category == "single" or category == "Single":
    cost = 20 * nights
  print(name + ", The total cost for you staying for" , nights , "nights will be £" , str(cost))
  return cost


#Main program
name()
category = bed_category()
nights = number_of_nights()
total_cost()
输出:

  File "python", line 27, in <module>
  File "python", line 19, in total_cost
TypeError: unsupported operand type(s) for +: 'function' and 'str'
 
文件“python”,第27行,在
文件“python”,第19行,总成本
TypeError:+:“function”和“str”的操作数类型不受支持
name+”中,您在“
停留的总成本,
name
指的是文件顶部的
def name():
。如果要获取其实际返回值,可以调用函数:

print(name() + ", The total cost for you staying for" , ...

当然,这只是假设您希望在这种情况下使用
name()
函数的返回值。不过,似乎您实际上是在尝试获取和设置不在函数范围内的变量,因为当它们不在范围内时,您也会引用
nights
category
。您应该使用一个类来存储结果,或者,或者您可以重新构造代码,像这里的另一个答案一样传递这些变量。

在函数
总成本
的范围内,没有声明
名称
变量,因此它假设它是第一行中定义的全局函数
名称
def name():

快速解决方案是在调用函数
name()
时将名称保存到变量,以便:

name = name()
category = bed_category()
nights = number_of_nights()
total_cost()
更优雅的解决方案是不使用全局变量,因此,将每个变量定义为
total_cost


def total_cost(selected_name, selected_category, selected_nights):
  cost = 40 * selected_nights
  if selected_category == "single" or selected_category == "Single":
    cost = 20 * selected_nights
  print(selected_name + ", The total cost for you staying for" , selected_nights, "nights will be £" , str(cost))
  return cost


#Main program
total_cost(name(), bed_category(), number_of_nights())

您需要初始化name,就像您的其他变量一样
name=name()
非常感谢!:)这将在打印输出时调用
name()
。OP希望程序首先询问您的姓名,但这将使程序第二次询问您的姓名。