here is the code=
def main():
print("Enter your age: ")
age= float(input())
while age >= 0:
if (age<= 2.00) :
print("The guest whose age is",age,"is admitted without charge.")
elif ((age>= 3.00) and (age<= 12.00)):
print("A(n)",age," year old will cost $14.00 dollars for admission.")
elif (age>=65.00) :
print("A(n)",age,"year old will cost $18.00 dollars for admission.")
else :
print("A(n)",age,"year old will cost $23.00 dollars for admission.")
print("End of guest list")
main()
and here is the problem I am trying to solve:
Create a program that begins by reading the ages of all of the guests in a group from the user, with one age entered on each line. The user will enter -1 to indicate that there are no more guests in the group. Then your program should display the admission cost for the group with an appropriate message. The cost should be displayed using two decimal places. Use the following sample run for input and output messages.
You need to move the prompt for input into the loop, otherwise age never changes within the while, creating an infinite loop.
def main():
age = 1
while age >= 0:
print("Enter your age: ")
age = float(input())
if (age<= 2.00) :
print("The guest whose age is",age,"is admitted without charge.")
elif ((age>= 3.00) and (age<= 12.00)):
print("A(n)",age," year old will cost $14.00 dollars for admission.")
elif (age>=65.00) :
print("A(n)",age,"year old will cost $18.00 dollars for admission.")
else :
print("A(n)",age,"year old will cost $23.00 dollars for admission.")
print("End of guest list")
main()
You never update age after its initial value and so the while loop continues forever, printing a line for each iteration.
You need to put a
age = float(input())
as the last line of the while loop.
Related
I have created a simple python program that lets users drive different cars. The user will enter their full name, address, and phone number. The user will then be asked which car they wish to drive, with a maximum of five selected cars. The cars have set prices and a total bill will be added up at the end of the program, however, I am currently unable to find a solution to work out the total cost for the user. The program also asks the user how many laps of the race they wish to perform in the car, I have already worked out how to display the total cost of the laps, but need it added to the total cost somehow. Thanks!
Code
cars_list = ["Lamborghini", "Ferrari", "Porsche", "Audi", "BMW"]
cars_prices = {"Lamborghini":50, "Ferrari":45, "Porsche":45, "Audi":30, "BMW":30}
laps_cost = 30
final_cost = []
final_order = {}
cust_num_cars = int(input("Please enter the number of cars you want to drive in this session: "))
while cust_num_cars > 5:
cust_num_cars = int(input("You can only drive a maximum of five cars! Please try again.\n Enter cars: "))
for index in range(cust_num_cars):
print("\nChoose a car type from the following list", cars_list)
select_cars = input("Select a car type: ")
if select_cars in cars_list:
print("\nYou have selected to drive the", {select_cars})
final_cost.append(cars_prices[select_cars])
if select_cars not in cars_list:
print("\n",{select_cars}, "is not in the available list of cars to drive!")
cust_name = input("\nPlease enter your full name: ")
cust_address = input("Please enter your full address: ")
cust_phone_num = int(input("Please enter your mobile phone number: "))
add_laps = input("\nWould you like to drive additional laps? (Yes/No): ")
if add_laps == "Yes":
print("\nYou have selected an additional lap!")
num_of_laps = int(input("Number of additional laps: "))
print("\nYou have selected", num_of_laps, "additional laps!")
final_cost.append(cars_prices[add_laps])
sum = num_of_laps * laps_cost
else:
print("\nYou have selected no additional extra laps.")
print("Total laps cost: £",final_cost)
print("\n----Order & Billing summary----")
print("Customer Full Name:", cust_name)
print("Customer Address:", cust_address)
print("Customer Phone Number", cust_phone_num)
print("Total cost", final_cost.append(cars_prices))
I have tried everything I know in my little experience with Python to work out a final cost. I have worked out the total cost for the number of laps, but can't work out how to add that to the cost of the selected cars and then display a total cost.
First, you can't use a for-loop because when you select a car that isn't in the possibilities you have lost an iteration, use a while loop
# final_cost renamed to car_cost
while len(car_cost) != cust_num_cars:
print("\nChoose a car type from the following list", cars_list)
select_cars = input("Select a car type: ")
if select_cars in cars_list:
print("\nYou have selected to drive the", select_cars)
car_cost.append(cars_prices[select_cars])
else:
print("\n", select_cars, "is not in the available list of cars to drive!")
Then use sum() for the cars cost and add to the laps cost
num_of_laps = 0
add_laps = input("\nWould you like to drive additional laps? (Yes/No): ")
if add_laps == "Yes":
print("\nYou have selected an additional lap!")
num_of_laps = int(input("Number of additional laps: "))
print("\nYou have selected", num_of_laps, "additional laps!")
else:
print("\nYou have selected no additional extra laps.")
total = num_of_laps * laps_cost + sum(car_cost)
print("Total price:", total)
To calculate the total cost, you can use the built-in sum() function, which takes an iterable (like a list) and returns the sum of all its elements. In your case, you can use it to add up all the prices of the cars that the user selected:
total_cost = sum(final_cost)
Then you can add the cost of the laps to the total cost. In your code, the variable sum holds the total cost of the laps. You can add that to the total_cost variable:
total_cost += sum
Hi friend in this program its better to add all of your costs in one variable.
in a list your list's elements are not adding together,
but with variables you can add your cost every time you get a cost like this:
cost_sum = 0
cost = input("Enter a cost: ")
cost_sum += cost
I am doing a project for class and can't figure out where I am going wrong. The code works in sections, but when I run it all together it shuts down right after the first input.
I think I need to call functions somewhere - but how and where?
Below is all my code so far, with comments.
import sys
#account balance
account_balance = float(500.25)
##prints current account balance
def printbalance():
print('Your current balance: %2g'% account_balance)
#for deposits
def deposit():
#user inputs amount to deposit
deposit_amount = float(input())
#sum of current balance plus deposit
balance = account_balance + deposit_amount
# prints customer deposit amount and balance afterwards
print('Deposit was $%.2f, current balance is $%2g' %(deposit_amount,
balance))
#for withdrawals
def withdraw():
#user inputs amount to withdraw
withdraw_amount = float(input())
#message to display if user attempts to withdraw more than they have
if(withdraw_amount > account_balance):
print('$%.2f is greater than your account balance of $%.2f\n' %
(withdraw_amount, account_balance))
else:
#current balance minus withdrawal amount
balance = account_balance - withdraw_amount
# prints customer withdrawal amount and balance afterwards
print('Withdrawal amount was $%.2f, current balance is $%.2f' %
(withdraw_amount, balance))
#system prompt asking the user what they would like to do
userchoice = input ('What would you like to do? D for Deposit, W for
Withdraw, B for Balance\n')
if (userchoice == 'D'): #deposit
print('How much would you like to deposit today?')
deposit()
elif userchoice == 'W': #withdraw
print ('How much would you like to withdraw today?')
elif userchoice == 'B': #balance
printbalance()
else:
print('Thank you for banking with us.')
sys.exit()
This part should be as one userchoice = input ('What would you like to do? D for Deposit, W for Withdraw, B for Balance\n')
Not sure if you indented by accident, but python does not like that.
Also, advice for your code. Make it so user can either do uppercase or lowercase letters for input, also make sure it still grab input even if user put empty spaces after input string.
Your withdraw exit the program after entering the string character W.
Balance is not grabbing the correct Deposit.
Use for loops and condition to keep it looping and ask user when to exit.
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 but this was originally course work and has now just become so random piece of Franken-Code. So I have the program take the users family name and date of arrival and use that as the file name. So naturally the program will be writing to a file that doesn't yet exist and if it does it should add another entry as to insure bookings aren't. All I have found is people saying one of 2 things, either that it "w" or "a" should create the file or that a "+" is needed after the selection of opening type like so "a+" or "w+". I think the earlier is more likely as I think "w+" is read/write but not to sure and many different sources say different things.
#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 need 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 re-enter stay in weeks -->"))
if nights >= 3:
discount_applic = 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, vaild 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.
The error:
Traceback (most recent call last):
File "H:\Computing\S4\Programs\Suite.py", line 89,
in storageFile = open(storageFileName, "w+")
FileNotFoundError: [Errno 2] No such file or directory: '15/10/17Daivdson.txt`'
print("Are you male or female?")
gender = input()
print("How old are you?")
age = input() ``
print("How many calories have you eaten today?")
calories = input()
if age in range(10-15) and gender == (Male):
print(2230 - calories)
This is the beginning of a code I have been trying to write where someone enters their gender, age and calories that they have eaten. I have been given data by my teacher that shows the amount of calories that each age group and gender should be eating. You then minus the calories they have eaten with the value they should be eating depending on their age and gender. It is very simple so the only age groups included are 11-14 and 15-18. The questions all run fine, but I can't get the main part of the code to run. It is on Python 3.3.3
You need to make following changes to your code.
print("Are you male or female?")
gender = input().lower()
print("How old are you?")
age = int( input() )
#convert input to int
print("How many calories have you eaten today?")
calories = int( input() )
#convert input to int
if age in [ x for x in range(10,15) ] and gender == "male":
print(2230 - calories)
You've got quite a few issues in your code. One, when you try to compare the value you get as age/calories, you're not converting them to ints first, and you can't compare an int and a string. Also, gender == (Male) compares the variable gender to the variable Male.
Here's a cleaned up version:
print("Are you male or female?")
gender = input()
while True:
try:
age = int(input("How old are you?"))
except ValueError:
print('Please enter a number for your age')
continue
else:
break
while True:
try:
calories = int(input("How many calories have you eaten today?"))
except ValueError:
print('Please enter a number for your calories eaten today')
continue
else:
break
if (10 < age < 15) and gender == 'male':
print(2230 - calories)
I have been trying to get this program to work, and it runs but once I got it to run I uncovered this problem. Right now it asks for gradePoint and credit hours and prints out a GPA like it is supposed to, but I can type anything in gradePoint and it will spit out a value. What I want is gradePoint to only work if the user types in a number between 0.0-4.0.
I was thinking of a loop of some sort, like an if loop but is there an easier way (or a preferred way) to do this?
Here's the code:
def stu():
stu = Student
class Student:
def __init__(self, name, hours, qpoints):
self.name = name
self.hours = float(hours)
self.qpoints = float(qpoints)
def getName(self):
return self.name
def getHours(self):
return self.hours
def getQpoints(self):
return self.qpoints
def getStudent(infoStr):
name, hours, qpoints = infoStr.split("\t")
return Student(name, hours, qpoints)
def addGrade(self, gradePoint, credits):
self.qpoints = gradePoint * credits
self.hours = credits
self.gradePoint = float(gradePoint)
self.credits = float(credits)
def gpa(self):
return self.qpoints/self.hours
def main():
stu = Student(" ", 0.0, 0.0)
credits = int(input("Enter Credit Hours "))
gradePoint = float(input("Enter Grade Point"))
if gradePoint > 4.0:
print("Please enter a Grade Point that is less then 4.")
stu.addGrade(gradePoint,credits)
output = stu.gpa()
print("\nStudent GPA is: ", output)
main()
This is the shell printout(I know the grade point is repeated in the GPA, this is for a class and we were supposed to use a skeleton program and change some things):
Enter Credit Hours 4
Enter Grade Point 3.5
Student GPA is: 3.5
Enter Credit Hours 12
Enter Grade Point 3.2
Student GPA is: 3.2
Thanks!
EDIT: I just did an if loop as suggested in the comments and it worked somewhat in that it printed out what I wanted but didn't make it stop and wait for the correct input. I'm not exactly sure how to get it to do that.
Here is the new print from the shell:
Enter Credit Hours 4
Enter Grade Point 3.5
Student GPA is: 3.5
Enter Credit Hours 4
Enter Grade Point 4.5
Please enter a Grade Point that is less then 4.
Student GPA is: 4.5
You can check if user input meet your requirements and throw an exception if not. This will make the program log an error message and stop on invalid user input.
The most basic way to do this is to use an assert statement:
def main():
stu = Student(" ", 0.0, 0.0)
credits = int(input("Enter Credit Hours "))
assert credits > 0 and credits < 4, "Please enter a number of Credit Hours between 0 and 4."
If you wish the application to keep prompting the user until a valid input is entered, you will need at least one while loop.
For exemple:
def main():
stu = Student(" ", 0.0, 0.0)
while True:
credits = int(input("Enter Credit Hours "))
if credits > 0 and credits < 4:
break
else:
print("Please enter a number of Credit Hours between 0 and 4")
while True:
gradePoint = float(input("Enter Grade Point"))
if gradePoint <= 4.0:
break
else:
print("Please enter a Grade Point that is less then 4.")
stu.addGrade(gradePoint,credits)
output = stu.gpa()
print("\nStudent GPA is: ", output)
Create a function that gathers a valid float from the user within a range:
def getValidFloat(prompt, error_prompt, minVal, maxVal):
while True:
userInput = raw_input(prompt)
try:
userInput = float(userInput)
if minVal <= userInput <= maxVal:
return userInput
else: raise ValueError
except ValueError:
print error_prompt
And then use like this:
gpa = getValidFloat(
"Enter Grade Point ",
"You must enter a valid number between 1.0 and 4.0",
1,
4)
The output would look something like this:
Enter Grade Point 6.3
You must enter a valid number between 1.0 and 4.0
Enter Grade Point 3.8