Get user input for function - python

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)

Related

Rounds integer even with float- python

Below is my code. the issue is in MAIN. The code works as a person trying to buy items into a cart and you can see the total price of those items. They have to enter in the price for each item that they want. If a person inputs a number to two decimal places, it rounds it to the nearest whole number.
import locale
class CashRegister:
def __init__(self):
mself.items = 0
self.price = int(float(0.00))
def addItems(self,price): #keeps track of total number of items in cart
self.price += price
self.items += 1
print(self.price)
def getTotal(self): #returns total price
return self.price
def getCount(self): #return the item count of the cart
return self.items
def clearCart(self): #clears cart for another user or checkout
self.items = 0
self.price = int(float(0.00))
def main():
user_name = input('What is your name?\n') #weclomes user
print("Hello",user_name)
locale.setlocale(locale.LC_ALL, 'en_US')
user_name = CashRegister() #user is using the cash register
while True:
line = input ("Would you like to add another food item to your cart? Choose y or n \n")
if line == "y":
** price = int(float(input("please input the price of the item\n")))
print(price)**
user_name.addItems(price) #user adds prices to cart
elif line == "n":
print("Your total checkout price:", locale.currency(user_name.getTotal()) )
# int(float(locale.currency(user_name.getTotal())))
print("Your total item count", user_name.getCount())
user_name.clearCart() #clears cart for another user/checkout
break
else:
print("Error")
if __name__ == '__main__':
main()
As soon as the person inputs the number, I printed it to see if that's where the problems lies. I'll enter 3.20 but it automatically converts it to 3. I have no idea how to force it to keep those decimals. I even tried printing it with the int/float and it still doesn't work.
The int() function always returns an integer. An integer never has any decimal points. So use only
float(input("please input the price of the item\n"))
instead of
int(float(input("please input the price of the item\n")))

How do I pass a return value in a function in a class to another function within the same class?

I'm working with and getting better at class objects and I started a new project that will check to see if the user is eligible for MIT or Harvard based on their GPA, SAT, and ACT scores (don't fact check me I thought this would just be a fun project and came up with the numbers off the top of my head)
I haven't started working on my Harvard Eligibility part of the project yet, so I'm only going to be using the MIT side.
This is my main file
#Inheritance
#8/28/2020
from mitstudent import mitstudent #This is importing both of the classes
from harvardstudent import harvardstudent
name = str(input("What is your name?: ")) #Asking the user's name to use as an argument for the parameter
while True: #This while loop using try and except to make sure that the user inputs a number instead of a string
try:
name = mitstudent()
except ValueError:
print("Input a number")
else:
break
print(mitstudent.eligible(name))
This is my mitstudent.py file that contains my class
#8/28/2020
#Inheritance
class mitstudent:
def __init__(self): #These are my class objects, the student will input their GPA, ACT score, and SAT score and the
#function will input it as the objects
self.gpa = float(input("What is your gpa?: "))
self.act = float(input("What is your ACT score?: "))
self.sat = float(input("What is your SAT score?: "))
'''
The next three class functions will be to check if the gpa, act, or sat scores are "eligible" for MIT if they are, the
function will return a value of "eligible" and if they aren't the function will return a value of "not eligible"
'''
def gpachecker(self):
if float(self.gpa) >= 3.5:
return "eligible"
else:
return "not eligible"
def actchecker(self):
if float(self.act) >= 33:
return "eligible"
else:
return "not eligible"
def satchecker(self):
if float(self.sat) >= 1400:
return "eligible"
else:
return "not eligible"
def eligible(self): #This function checks to see if the student has met all of the requirements to be eligible for
#Mit, which includes a gpa over 3.5, an act score over 33, and an sat score over 1400
if mitstudent.gpachecker and mitstudent.actchecker and mitstudent.satchecker == "eligible":
return "This student is eligible for MIT"
else:
return "This student is ineligible for MIT"
In the main file, I set a name and inputted 9999 for all of the objects, however it still says the student is ineligible.
I believe it is because the return statement within the gpachecker (act & sat aswell) function is not actually returning the way I want it to. Is there a way I can return the statement from those functions
def gpachecker(self):
if float(self.gpa) >= 3.5:
return "eligible"
else:
return "not eligible"
for it to actually be used in this if statement?
def eligible(self): #This function checks to see if the student has met all of the requirements to be eligible for
#Mit, which includes a gpa over 3.5, an act score over 33, and an sat score over 1400
if mitstudent.gpachecker and mitstudent.actchecker and mitstudent.satchecker == "eligible":
return "This student is eligible for MIT"
else:
return "This student is ineligible for MIT"
I think the problem lies in your if statement.
if mitstudent.gpachecker and mitstudent.actchecker and mitstudent.satchecker == "eligible":
The condition will be evaluated like this:
mitstudent.gpachecker and mitstudent.actchecker and (mitstudent.satchecker == "eligible")
First of all, if you want to get the value returned by the methods, you have to call it using self.method_name().
While the values for mitstudent.gpachecker, mitstudent.actchecker, and mitstudent.satchecker will always be True since they pertain to the methods of the class, (mitstudent.satchecker == "eligible") is always False given that mitstudent.satchecker is a function, not a string.
A solution would be something like:
if self.gpachecker() == "eligible" and self.actchecker() == "eligible" and self.satchecker() == "eligible":
You may also want to modify your checker methods to return Boolean(True or False) values instead of strings so that your condition would become shorter:
if self.gpachecker() and self.actchecker() and self.satchecker():

Holiday application on Python 2.7

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!

Python: setting max for bank withdraw

I'm new to python and I am still trying to get the hang of it. I'm attempting to change the processing function in the following code so that the user can not withdraw more money then what the "bank" has on record, which is 500. I was hoping that someone could help. Would I enter an if statement for >500?
#Simple Bank Atm
def main():
PIN=7777;balance=500;pin=0;success=False
Pin=getInput(pin)
Pin,PIN,balance,success=processing(pin,PIN,balance,success)
Display(success,balance)
#Input Function
def getInput(pin):
pin=int(input(“Please enter your PIN:”))
return pin
#Processing Function
def processing(pin,PIN,balance,success):
if pin==PIN:
success=True
amt=float(input(“How much would you like to withdraw?”))
balance=balance-amt
return pin,PIN,balance,success
else:
success=false
return pin,PIN,balance,success
You can use an if condition to do this.
if amt <= balance: #Can't withdraw over your current balance
balance -= amt
else:
print("Error. Amount exceeds funds on record.")
Also, other things aside you're returning the same thing inside your if and else condition and if this is what you really want to return it's redundant to have it in both. You can just have it after your else statement at the same indentation level
def main():
PIN=7777;balance=500;pin=0;success=False
Pin=getInput(pin)
Pin,PIN,balance,success=processing(pin,PIN,balance,success)
Display(success,balance)
#Input Function
def getInput(pin):
pin=int(input("Please enter your PIN:"))
return pin
#Processing Function
def processing(pin,PIN,balance,success):
if pin==PIN:
success=True
amt=float(input("How much would you like to withdraw?"))
if balance<amt:
print("Amount to draw is greater than balance.")
return pin,PIN,balance,false
balance=balance-amt
return pin,PIN,balance,success
else:
success=false
return pin,PIN,balance,success
Yes. You should use an if statement - this should happen before they can withdrawal the amount (balance = balance - amt).
So you could do something like this:
if amt <= balance:
balance -= amt
return True
else:
# do not change balance and stop withdrawal
return False

NameError: Global Name not defined

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.

Categories