I have tried solve these tasks for a homework but I got stuck:
You will need to to create four functions:
Hotel cost - This function will take the number of nights as an argument and return a total cost (You can choose the price per a night)
Plane cost - This function will take the city you are flying to as an argument and return a cost for the flight (Hint: use if/else if statements in the function to retrieve a price based on the chosen city)
Car rental - This function will take the number of days as an argument and return the total cost.
Holiday cost - This function will take three arguments, number of nights, city, and days.
Using these three arguments, you can call all three of the above functions with respective arguments and finally return a total cost for your holiday.
Print out the value of your Holiday function to see the result!
Try using your app with different combinations to show it’s compatibility
with different options
This is what I have so far:
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
The error I get is the following:
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
You already call the 3 other functions inside holiday_cost. You don't need to call them multiple times.
Also ive made a few other helpful changes such as while city > 3: instead of while city != 4: in plane_cost() and I added a return ticket line at the end of plane_cost()
Also the line:
elif city == '4':
print 'You have selected an invalid option'
was unnecessary as city == '4' falls into the else condition.
Here is the final code:
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
You wrote:
total = holiday_cost(nights, city, days)
but nights, city, days are not defined. You used those names to define the input parameters but that does not define those variables outside the functions where they are used.
In other words
def someFunction(inputP):
#here inputP is defined
...
#her inputP is not defined
To return to your question you must assign the returned value to those variables:
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?: ')))
Since it is easy to get lost in Python I suggest using different names for variables in different scope: do not use nights for example in hotel_cost then twice in holiday_cost and then another time in the global scope.
Cheers!
You have to save the values you asked in variables:
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?: ')))
total = holiday_cost(nights, city, days)
Regards!
Related
I have to write a program that writes a file for a company and analyzes the sales data.
request_countryname function has to validate the user's input is at least 2 characters long
request_sales function has to accept 2 parameters (product and country), request the user for input on the total sales for each product of that country, and validate that the amount is numeric and non negative
request_data function will iteratively request country names from the user using the above functions and will ask if the user wants to add another country. Once the user is finished, the program will display how many records were added to the file. The program will write a file name (sales_data.txt)
analyze_data function will calculate the average sales per country for each type of product, total amount of sales for each product type, and total amount of sales
I am having trouble with the analyze_data function. I keep getting an error saying some of my variable from the request_data function are undefined. I believe this is happening because these variables (such as software_accumulator) are defined locally, not globally. I tried calling the request_data function at the beginning of my analyze_data function to call the information I wrote in the file, but I am still getting an error. I am also not sure if I correctly used accumulators to calculate the totals for each product type.
How do I fix this?
#Request country name from user
#Country name must be at least 2 characters long
def request_countryname():
character_length = 2
while True:
country = input("Please enter the country's name: ")
if len(country) < character_length or not country.isalpha():
print("Name must be at least 2 characters.")
else:
return country
#Request total sales for each product type for the user's country
#Input must be numeric and non negative
def request_sales(product, country_name):
flag = -1
while flag < 0:
sales = input("Please enter the total sales for " + product + " in " + country_name + ": $ ")
try:
sales = float(sales)
except ValueError:
print("Amount must be numeric")
else:
if sales < 0 :
print("Amount must be numeric and and non-negative. ")
else:
flag = 1
return sales
#Iteratively requests country names from the user and asks for totals
#Once the user finishes inputting countries, program will store data to a file
#Program will display total number of records added
def request_data(sales_data):
sales_data = open(sales_data, "w")
count = 0
software_accumulator = 0
hardware_accumulator = 0
accessories_accumulator = 0
again = "y"
while again == "y" or again == "Y":
country_name = request_countryname()
software = request_sales("software", country_name)
hardware = request_sales("hardware", country_name)
accessories = request_sales("accessories", country_name)
#Write data to file
sales_data.write(country_name + '/n')
sales_data.write(software + '/n')
sales_data.write(hardware + '/n')
sales_data.write(accessories + '/n')
count += 1
software_accumulator += software
hardware_accumulator += hardware
accessories_accumulator += accessories
#Request country names from user
again = input("Do you want to add another country? (Enter y/Y for Yes: ")
#Displays total number of records added
print(count, " record(s) successfully added to file")
sales_data.close()
#Calculates and displays information
def analyze_data(sales_data):
sales_data = open(sales_data, "r")
sales_data = request_data(sales_data)
#Calculates total software of all country inputs
total_software = software_accumulator
#Calculates total hardware of all country inputs
total_hardware = hardware_accumulator
#Calculates total accessories of all country inputs
total_accessories = accessories_accumulator
#Calcuates average software
average_software = total_software / count
#Calcuates average hardware
average_hardware = total_hardware / count
#Calcuates average accessories
average_accessories = total_accessories / count
#Calculates total sales
total_sales = total_software + total_hardware + total_accessories
#Prints and displays calculations
print("----------------------------")
print()
print("Average software sales per country: $ ", format(average_software, ',.2f'))
print("Average hardware sales per country: $ ", format(average_hardware, ',.2f'))
print("Average accessories sales per country: $ ", format(average_accessories, ',.2f'))
print()
print("Total software sales: $ ", format(total_software, ',.2f'))
print("Total hardware sales: $ ", format(total_hardware, ',.2f'))
print("Total accessories sales: $ ", format(total_accessories, ',.2f'))
print()
print("Total sales: $ ", format(total_sales, ',.2f'))
#Defines main function
def main():
request_data("sales_data.txt")
analyze_data("sales_data.txt")
#Calls main function
main()
You are correct in your hunch it has to do with the scope the variable are in, pay attention to where you define your variables, once you exit a function all variables in that functions scope will be gone. Don't use global variables, but return values you need from a function.
I suggest using an IDE to develop in as well, they will tell you when you are accessing a variable that is not in scope (ie not defined) - PyCharm or VSCode are both highly accessible
IDE says function isn't returning value
IDE says variable not defined
I've been writing a program as part of a school course and decided to make it a bit more extensive than I needed to. So for the better part of 3 months I've been slowly adding stuff in an attempt to make the system output a file to save that is human readable.
I could save this all under one file as previous programs I've written have but I can only get better if I try. So I have the program take the users family name and date of arrival and use that as the file name. I have the program concatenate these variables (both strings) with ".txt" at the end and save this as a variable I then use to name the file I want to write to. Issue is it spits out the error that "decoding strings is not supported". Just for reference the program is made to get a booking for a hotel-like thing and spit out the price, arrival date, name etc. and just print it but as I've said I'm overambitious. Also I apologise about the bad code, just started to learn this year and a bit. Any help appreciated. Having to run it through Python 3.3.0:
#Comment Format
#
#Code
#
#Comment about above Code
from random import*
c_single = 47
c_double = 90
c_family = 250
discount = 10
VAT = 20
max_stay = 14
min_stay = 1
room_list = []
min_rooms = 1
max_rooms = 4
cost = 0
#Sets all needed variables that would need to be changed if the physical business changes (e.g. Increase in number of rooms, Longer Max stay allowed, Change to Pricing)
print("Cost of room:")
print("Single - £", c_single)
print("Double - £", c_double)
print("Family - £", c_family)
#Prints prices based on above variables
name = input("What is the family name --> ")
arrival = input("Please enter date of arrival in the form dd/mm/yy --> ")
while len(arrival) != 8:
arrival = input("Please re-enter, in the case of the month or day not being 2 digits long insert a 0 before to insure the form dd/mm/yy is followed --> ")
#Gets the guests name and date of arrival for latter update into the business' preferred method of storage for bookings
nights = int(input("How many nights do you intend to stay in weeks --> "))
while nights > max_stay or nights < min_stay:
nights = int(input("That is too short or long, please reneter stay in weeks -->"))
if nights >= 3:
discount_aplic = 1
#Gets the guests ideal number of weeks stay, ensure that this would be possible then adds the discount if applicable
rooms = int(input("Please enter number of rooms required --> "))
while rooms < min_rooms or rooms > max_rooms:
rooms = int(input("That number of rooms is unachievable in one purchase, please re-enter the number of rooms you require --> "))
#Gets number of rooms desired and checks that it does not exceed the maximum allowed by the business or the minimum (currently 1, staying no nights doesn't work)
for room in range (rooms):
current_room = input("Please enter the room desired--> ")
current_room = current_room.upper()
if current_room == "SINGLE":
cost += c_single
elif current_room == "DOUBLE":
cost += c_double
elif current_room == "FAMILY":
cost += c_family
#Checks which room is desired
else:
while current_room != "SINGLE" and current_room != "DOUBLE" and current_room != "FAMILY":
current_room = input("Invalid room type, valid entries are : single, double or family --> ")
current_room = current_room.upper()
#Ensures that the desired room is valid, if first inserted not correctly, repeats until valid entry is entered
room_list.append (current_room)
#Adds the wanted room type to the array room_list
cost = cost * nights
#calculates cost
booking = randrange(1000,9999)
print("Name: ", name)
print("You have booked from ", arrival)
print("You have booked stay for ", nights, "weeks")
print("You have booked", rooms, " room/s of these categories;")
print(str(room_list))
print("This will cost £", cost)
print("Booking referral: ", booking)
#Prints booking information
dateStr = str(arrival)
storageFileName = str(dateStr, name,".txt")
storageFile = open(storageFileName, "w")
storageFile.write("Name: ", name)
storageFile.write("They have booked from ", arrival)
storageFile.write("They have booked stay for ", nights, "weeks")
storageFile.write("They have booked", rooms, " room/s of these categories;")
storageFile.write(str(room_list))
storageFile.write("This has cost them -- >£", cost)
storageFile.write("Booking referral: ", booking)
#saves the storage data to a server under the name and data.
storageFileName = str(dateStr, name,".txt")
Calling str with more than one argument will not convert each argument to a string and combine them. What you're actually doing here is calling str with the parameters str(bytes_or_buffer, encoding, errors). According to the documentation:
>>> help(str)
Help on class str in module builtins:
class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
Since you're specifying encoding and errors, the first argument can't be a string, because a string isn't a data buffer. This explains the error decoding str is not supported.
If you are trying to concatenate strings together, you should use the + operator, or the format method:
storageFileName = dateStr + name + ".txt"
Or
storageFileName = "{}{}.txt".format(dateStr, name)
So my friend and I have been working on this problem for a few days now for our Intro to Python class at our college, but we are a bit stuck due to the fact we didn't spend much time on this topic in class. Our problem is this, "Every product ID must be six characters long and starts with three upper case letters followed by three digits. For example ABE123 and PPL334 are valid product IDs but ABE1.2 and P1L3R4 are not. The auction site has a minimum bid price of 5 dollars and caps bids at 500 dollars. Bids with dollars and cents are acceptable. For example 6.78 is a valid bid. The following code reads in bids from the prompt (keyboard inputs) and loads the product ids and bidding prices into two lists products and bids. Unfortunately the code contains no input validation which is your job to complete." Our teacher gave us the code, we just have to validate the inputs. But it has to be done outside of her code, as in its own function. Here is the code:
`def getbids():
products = []
bids = []
answer = "yes"
while answer == "yes":
productid = input("Enter the productID ")
bid = float(input("Enter the bid for one item "))
products.append(productid)
bids.append(bid)
answer = input("Are there more bids? ")
return products, bids`
Basically, our job is to validate the productid and the bid in separate functions. I have our code here but what we have doesn't work completely and is not correct.
Here is the one for productId:
`def validprod(n):
caps="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
nums="0123456789"
m="Error"
if len(n)!=6:
print("Error, productID must be 6 digits,3 capital letters followed by 3 numbers")
return m
else:
while len(n)==6:
for i in range(3):
if n[i] not in caps or n[i+3] not in nums:
print("Error, productID must be 6 digits,3 capital letters followed by 3 numbers")
return m
else:
return n`
Here is the one for bids:
`def validbid(x,y):
bid="Error"
while x=="Error":
return bid
while x!="Error":
if y>500 or y<5:
print("Error, bid must be between 5 and 500(do not include a dollar sign with your bid).")
return bid
else:
return y`
We know there is probably a much simpler way to do it, we just don't know it.
import re
pid_regex = re.compile(r'^[A-Za-z]{3}\d{3}$')
def is_valid_pid(pid):
if pid_regex.match(pid):
return True
return False
def is_valid_bid(bid):
return bid >= 5 and bid <= 500
def getbids():
products = []
bids = []
answer = "yes"
while answer == "yes":
productid = input("Enter the productID ")
products.append(productid)
bid = float(input("Enter the bid for one item "))
bids.append(bid)
answer = input("Are there more bids? ")
return products, bids
products = dict(zip(*getbids()))
for pid in products:
bid = products[pid]
if not is_valid_pid(pid):
print('PID {} is invalid.'.format(pid))
break
elif not is_valid_bid(bid):
print('PID {} has an invalid bid {}'.format(pid, bid))
break
else:
print('PID {} to bid {} seems OK.'.format(pid, bid))
Note: I needed to fix your getbids() function, because products were not being appended to the products list.
Another note: If you believe I was wrong to provide a complete solution, please let me know. I'm completely open to feedback from the public.
I am trying to learn python using codeacdemy. This was one of their excercises. Basically they had me create 4 different functions that calculated the total cost. But there was no option to ask the user to manually enter in the values. So thats what I am trying to to. The code is right upto the return rental-car_cost part. its just the bottom bit where I am having trouble.
print "this code calculates the total price of a trip, using 4 functions"
def hotel_cost(nights):
return 140*nights
def plane_ride_cost(city):
if (city=="Charlotte"):
return 183
elif(city=="Tampa"):
return 220
elif(city=="Pittsburgh"):
return 222
elif(city=="Los Angeles"):
return 475
def rental_car_cost(days):
cost=days*40
if (days>=7):
cost -= 50
elif(days>=3):
cost -=20
return cost
def trip_cost(city,days,spending_money):
return rental_car_cost(days)+hotel_cost(days)+ plane_ride_cost(city)+spending_money
city= raw_input("enter city name")
days= raw_input("enter number of days staying")
spending_money= raw_input("enter spendig money")
print trip_cost(city,days, spending_money)
this was the original code and it rune perfectly fine. All i want to do is have the user enter the values when the code it running.
def hotel_cost(nights):
return 140*nights
def plane_ride_cost(city):
if (city=="Charlotte"):
return 183
elif(city=="Tampa"):
return 220
elif(city=="Pittsburgh"):
return 222
elif(city=="Los Angeles"):
return 475
def rental_car_cost(days):
cost=days*40
if (days>=7):
cost -= 50
elif(days>=3):
cost -=20
return cost
def trip_cost(city,days,spending_money):
return rental_car_cost(days)+hotel_cost(days)+ plane_ride_cost(city)+spending_money
print trip_cost("Los Angeles",5,600)
Equal question:
Vacation price program Python
Propose
Consider it only like some to improve this code. I think so it didn't answer your question.
I don't know what propose of Code Academy for that exercise but some way easier and cleaner is at below:
print "this code calculates the total price of a trip, using 4 functions"
def hotel_cost(nights):
return 140 * nights
def plane_ride_cost(city):
#So you can create dict and put for each city
#Key - name of city
#value - cost
CITY_COST = {
"Charlotte": 183,
"Pittsburgh" : 222,
"Los Angeles" : 475,
"Tampa": "220"
}
#Method from dict
#if city doesn't exists it'll return False
#The second param is default return if doesn't exist key into dict
#you can change if do you want
return CITY_COST.get(city, False)
def rental_car_cost(days):
cost = days * 40
if (days >= 7):
cost -= 50
elif(days >=3 ):
cost -=20
return cost
def trip_cost(city,days,spending_money):
return rental_car_cost(days)+hotel_cost(days)+ plane_ride_cost(city)+spending_money
city= raw_input("enter city name")
days= raw_input("enter number of days staying")
spending_money= raw_input("enter spendig money")
print trip_cost(city,days, spending_money)
Documentation about Dict
https://docs.python.org/2/tutorial/datastructures.html#dictionaries
Try using int(raw_input(enter number of days staying")) or input("enter number of days staying") instead of raw_input("enter number of days staying") What happens ? You see any difference ? This is because raw_input() converts input data into string but it's not the same with input(). Find out the differences between input() and raw_input() and how it has changed as python has evolved. I have made some changes to the code as shown below. It runs perfectly without errors. Let me know if it helped you.
print "this code calculates the total price of a trip, using 4 functions"
def hotel_cost(nights):
return 140*nights
def plane_ride_cost(city):
if (city=="Charlotte"):
return 183
elif(city=="Tampa"):
return 220
elif(city=="Pittsburgh"):
return 222
elif(city=="Los Angeles"):
return 475
def rental_car_cost(days):
cost=days*40
if (days>=7):
cost -= 50
elif(days>=3):
cost -=20
return cost
def trip_cost(city,days,spending_money):
return rental_car_cost(days)+hotel_cost(days)+ plane_ride_cost(city)+spending_money
city= raw_input("enter city name")
days= int(raw_input("enter number of days staying")) ##### notice here
spending_money= int(raw_input("enter spendig money")) ### and here too
print trip_cost(city,days, spending_money)
Instead of the above you can use the following code too.
################## without type casting#############
city= raw_input("enter city name")
days= input("enter number of days staying") ##### notice something here
spending_money= input("enter spendig money") ### and here
print trip_cost(city,days, spending_money)
my python code keeps getting nameerror, global variable not defined on ticketSold. I am not sure how to fix this, as I did define it as a global variable. Any help is appreciated.
aLimit=300
bLimit=500
cLimit=100
aPrice=20
bPrice=15
cPrice=10
def Main():
global ticketSold
getTickets(aLimit)
sectionIncome=calcIncome(ticketSold,aPrice)
SectionIncome+=totalIncome
print("The theater generated this much money from section A "+str(sectionIncome))
getTickets(bLimit)
sectionIncome=calcIncome(ticketSold,bPrice)
SectionIncome+=totalIncome
print("The theater generated this much money from section B "+str(sectionIncome))
getTickets(cLimit)
sectionIncome=calcIncome(ticketSold,cPrice)
sectionIncome+=totalIncome
print("The theater generated this much money from section C "+str(sectionIncome))
print("The Theater generated "+str(totalIncome)+" total in ticket sales.")
def getTickets(limit):
ticketSold=int(input("How many tickets were sold? "))
if (ticketsValid(ticketSold,limit)==True):
return ticketSold
else:
getTickets(limit)
def ticketsValid(ticketSold,limit):
while (ticketSold>limit or ticketSold<0):
print ("ERROR: There must be tickets less than "+str(limit)+" and more than 0")
return False
return True
def calcIncome(ticketSold,price):
return ticketSold*price
Saying global varname does not magically create varname for you. You have to declare ticketSold in the global namespace, for example after cPrice=10. global only makes sure that when you say ticketSold, you're using the global variable named ticketSold and not a local variable by that same name.
Here is a version which:
is Python 2 / 3 compatible
does not use any global variables
is easily extended to any number of sections
demonstrates some benefits of OOP (as opposed to a proliferation of named variables: aLimit, bLimit, etc - what will you do when you reach 27 sections?)
And so:
import sys
if sys.hexversion < 0x3000000:
# Python 2.x
inp = raw_input
else:
# Python 3.x
inp = input
def get_int(prompt):
while True:
try:
return int(inp(prompt))
except ValueError: # could not convert to int
pass
class Section:
def __init__(self, name, seats, price, sold):
self.name = name
self.seats = seats
self.price = price
self.sold = sold
def empty_seats(self):
return self.seats - self.sold
def gross_income(self):
return self.sold * self.price
def sell(self, seats):
if 0 <= seats <= self.empty_seats():
self.sold += seats
else:
raise ValueError("Cannot sell {} seats, only {} are available".format(seats, self.empty_seats))
def main():
# create the available sections
sections = [
Section("Loge", 300, 20., 0),
Section("Floor", 500, 15., 0),
Section("Wings", 100, 10., 0)
]
# get section seat sales
for section in sections:
prompt = "\nHow many seats were sold in the {} Section? ".format(section.name)
while True:
# prompt repeatedly until a valid number of seats is sold
try:
section.sell(get_int(prompt))
break
except ValueError as v:
print(v)
# report section earnings
print("The theatre earned ${:0.2f} from the {} Section".format(section.gross_income(), section.name))
# report total earnings
total_earnings = sum(section.gross_income() for section in sections)
print("\nTotal income was ${:0.2f} on ticket sales.".format(total_earnings))
if __name__=="__main__":
main()
which gives us
How many seats were sold in the Loge Section? 300
The theatre earned $6000.00 from the Loge Section
How many seats were sold in the Floor Section? 300
The theatre earned $4500.00 from the Floor Section
How many seats were sold in the Wings Section? 100
The theatre earned $1000.00 from the Wings Section
Total income was $11500.00 on ticket sales.