我尝试过为家庭作业解决这些任务,但我陷入困境:
您需要创建四个功能:
使用这三个参数,您可以使用相应的参数调用上述所有三个函数,最后返回假期的总成本。
打印出假日功能的值以查看结果!
尝试使用不同组合的应用来展示其兼容性 有不同的选择
这是我到目前为止所做的:
def hotel_cost(nights):
return nights * 875
def plane_cost(city):
ticket = 0
while city != 4:
if city == '1':
ticket = 750
break
elif city == '2':
ticket = 850
break
elif city == '3':
ticket = 600
break
elif city == '4':
print 'You have selected an invalid option'
else:
print 'You have selected an invalid option'
def car_rental(days):
return days * 275
def holiday_cost(nights, city, days):
nights = hotel_cost(nights)
city = plane_cost(city)
days = car_rental(days)
return nights + city + days
hotel_cost(int(raw_input('How many nights will you be staying? ')))
plane_cost(raw_input('\n1. O.R. Tambo International\n2. Capetown International\n3. King Shaka International\nWhere you flying to? '))
car_rental(int(raw_input('How many days will you need a car for?: ')))
total = holiday_cost(nights, city, days)
print total
我得到的错误如下:
Traceback (most recent call last): File "C:\Users\user\Dropbox\Mengezi Dlomo-9897\intro to programming\Task 24\holiday.py", line 37, in <module> total = holiday_cost(nights, city, days) NameError: name 'nights' is not defined
答案 0 :(得分:0)
您已经在holiday_cost中调用了其他3个函数。你不需要多次打电话给他们。
我还在plane_cost()中进行了一些其他有用的更改,例如while city > 3:
而不是while city != 4:
,并在plane_cost()的末尾添加了return ticket
行
还行:
elif city ==&#39; 4&#39;:
打印&#39;您选择了无效选项&#39;
没有必要因为城市==&#39; 4&#39;落入else
条件。
以下是最终代码:
def hotel_cost(nights):
return nights * 875
def plane_cost(city):
ticket = 0
while city > 3:
if city == '1':
ticket = 750
break
elif city == '2':
ticket = 850
break
elif city == '3':
ticket = 600
break
else:
print 'You have selected an invalid option'
return ticket
def car_rental(days):
return days * 275
def holiday_cost(nights, city, days):
nights = hotel_cost(nights)
city = plane_cost(city)
days = car_rental(days)
return nights + city + days
nights = int(raw_input('How many nights will you be staying? '))
city = raw_input('\n1. O.R. Tambo International\n2. Capetown International\n3. King Shaka International\nWhere you flying to? ')
days = int(raw_input('How many days will you need a car for?: '))
total = holiday_cost(nights, city, days)
print total
答案 1 :(得分:0)
您写道:
total = holiday_cost(nights, city, days)
但未定义nights, city, days
。您使用这些名称来定义输入参数,但不会在使用它们的函数之外定义这些变量。
换句话说
def someFunction(inputP):
#here inputP is defined
...
#her inputP is not defined
要回到您的问题,您必须将返回的值分配给这些变量:
nights = hotel_cost(int(raw_input('How many nights will you be staying? ')))
city = plane_cost(raw_input('\n1. O.R. Tambo International\n2. Capetown International\n3. King Shaka International\nWhere you flying to? '))
days = car_rental(int(raw_input('How many days will you need a car for?: ')))
由于很容易迷失在Python中,我建议为不同范围的变量使用不同的名称:不要在nights
中使用hotel_cost
,而在holiday_cost
中使用两次,然后使用另一个时间在全球范围内。
干杯!
答案 2 :(得分:0)
您必须在变量中保存您要求的值:
crontab
问候!