How do I loop to prevent wrong user input? - python

Hi all! My goal is to loop age so that male_cal or fem_cal (implicit) print correctly. Please help! Much thanks --> Pythonidaer <--
print("\nWelcome to the Daily Caloric Intake Calculator!")
I don't know how to loop age like I did sex.
age = int(input("\nHow old are you in years? "))
sex = input("\nAre you a male or a female? Enter 'male' or 'female'. ").lower()
if sex == "female" or sex == "f":
sex = "female"
elif sex == "male" or sex == "m":
sex = "male"
else:
sex = input("Sorry, there's only two choices: MALE or FEMALE. ").lower()
The equation requires age be an integer. How can I foolproof?
height = float(input("\nHow tall are you in inches? "))
metric_height = float(height * 2.54)
weight = float(input("\nWhat is your weight in pounds? "))
metric_weight = int(weight * 0.453592)
activity_level = float(input("""
Please select your activity level:
Sedentary (enter '1.2')
Moderatively Active (enter '1.3')
Active? (enter '1.4')
"""))
male_cal = 10 * metric_weight + 6.25 * metric_height - 5 * age - 161
fem_cal = 10 * metric_weight + 6.25 * metric_height - 5 * age + 5
if (sex == "male"):
carbs = int(male_cal * .45)
protein = int(male_cal * .20)
fats = int(male_cal * .35)
print("\nYour DCI should be: ", int(male_cal), "calories a day.")
print(f"""\nThat means getting:
{carbs} cals from carbs,
{fats} cals from fats, and
{protein} cals from protein.""")
elif (sex == "female"):
carbs = int(fem_cal * .45)
protein = int(fem_cal * .20)
fats = int(fem_cal * .35)
print("\nYour DCI should be: ", int(fem_cal), "calories a day.")
print(f"""\nThat means getting:
{carbs} cals from carbs,
{fats} cals from fats, and
{protein} cals from protein.""")

while True:
try:
age = int(input("\nHow old are you in years? "))
break
except ValueError:
print('please put in a number')
This should do the Trick

Related

How can I resolve no print output of float value commission with arrays?

I am currently working on improving my commission program by implementing arrays into my program. However, I cannot properly display my commission results anymore. If I revert some array changes, I can display my commission fine. Where did I do wrong? I would appreciate any feedback on my code posted below. I'm a beginner and have included code that I have learned up to this point.
MAX = 10
def main():
comp_name = [""] * MAX
sales_amount = [0.0] * MAX
total_sales_amount = 0.0
commission = 0.0
bonus = 0.0
more_sales = 'Y'
select_item = 0
welcome_message()
while more_sales == 'Y':
comp_name[select_item] = get_comp_name()
sales_amount[select_item] = get_sales_amount()
total_sales_amount = total_sales_amount + (sales_amount[select_item] + sales_amount[select_item])
more_sales = more_sales_input()
select_item = select_item + 1
commission += get_commission_calc(sales_amount[select_item])
print_receipt(comp_name, sales_amount, commission, select_item)
bonus = get_bonus(commission)
commission = commission + bonus
print_totals(bonus, commission)
def print_receipt(comp_name, sales_amount, total_commission, select_item):
sub_total = 0
count = 0
print("\nCompany Name Sales Your Commission")
print("------------ ----- ---------------")
while count < select_item:
print("{0:<15}".format(comp_name[count]), "\t\t$ ", format(sales_amount[count], ".2f"), "\t$ ", format(sales_amount[count], ".2f"))
sub_total = sub_total + (sales_amount[count])
count = count + 1
print("-----------------------------------------------")
print("Collect: $", format(total_commission, ".2f"))
def get_comp_name():
comp = ""
comp = input("\nEnter Company name: ")
return comp
def more_sales_input():
more = ""
more = input("Do you have more sales to add? (y/n): ")
more = more.upper()
while more != "Y" and more!= "N":
print("Invalid entry, either y or n.")
more = input("Do you have more sales to add? (y/n): ")
more = more.upper()
return more
def get_sales_amount():
sales = 0.0
while True:
try:
sales = float(input("Please enter sales $ "))
if sales < 0:
print("Invalid, must be a positive numeric!")
else:
return sales
except:
print("Invalid, must be a positive numeric!")
def get_commission_calc(sales):
commission = 0.0
if sales >= 20000:
commission = sales * .10
elif sales >= 10000:
commission = sales * .07
else:
commission = sales * .05
return commission
def get_bonus(commission):
if commission >= 1000:
return + 500
else:
return 0
def print_totals(bonus, total_commission):
if bonus > 0:
print("\nYou earned a $500 bonus added to your pay!")
else:
print("\nYou did not yet meet requirements for a bonus!")
print("\nYour commission is", '${:,.2f}'.format(total_commission))
main()

trying to write a food ordering sys for homework in python

im learning python and for my homework i wanna make a food ordering program and get the receipt of the products purchased with the prices for the total. im struggling to get the billing process as i cannot get all the products chosen by the user displayed on the receipt
import datetime
x = datetime.datetime.now()
name = input("Enter your name: ")
address = input("Enter your address: ")
contact = input("Enter your phone number: ")
print("Hello " + name)
print("*"*31 + "Welcome, these are the items on on the menu."+"*" * 32 )
print("Menu:\n"
"1.Burger:150.\n"
"2.Fried Momo:120.\n"
"3.coffee:60.\n"
"4.Pizza:180.\n"
"5.Fried Rice:150.\n"
"6.French Fries:90.\n"
"7.Steamed Dumplings:150.\n"
"8.Chicken drumsticks:120.\n"
"9.Chicken Pakoras:120.\n"
"10.American Chop Suey:200.\n")
prices = {"1.Burger":150,
"2.Fried Momo":120,
"3.coffee":60,
"4.Pizza":180,
"5.Fried Rice":150,
"6.French Fries":90,
"7.Steamed dumplings":150,
"8.Chicken drumsticks":120,
"9.Chicken Pakoras":120,
"10.American Chop Suey":200
}
continue_order = 1
total_cost, total = 0, 0
cart = []
while continue_order != 0:
option = int(input("Which item would you like to purchase?: "))
cart.append(option)
if option >= 10:
print('we do not serve that here')
break
elif option == 1:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: ₹" + str(total))
elif option == 2:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 3:
quantity = int(input("Enter the quantity: "))
total = quantity * 60
print("The price is: " + str(total))
elif option == 4:
qquantity = int(input("Enter the quantity: "))
total = quantity * 180
print("The price is: " + str(total))
elif option == 5:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: " + str(total))
elif option == 6:
quantity = int(input("Enter the quantity: "))
total = quantity * 90
print("The price is: " + str(total))
elif option == 7:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: " + str(total))
elif option == 8:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 9:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 10:
quantity = int(input("Enter the quantity: "))
total = quantity * 200
print("The price is: " + str(total))
total_cost += total
continue_order = int(input("Would you like another item? enter Yes--> (1) or--> No (0):"))
print('='*30)
print('='*30)
print("Your receipt:\n")
print("Date: " + str(x))
print("Name: " + name.title())
print("Adress: " + address)
print("Contact number: " + contact)
for option in cart:
print ("Item: %s. Price: %s") % (option, prices[option])
print("Quantity: ",quantity)
print("Total Price: ", total_cost)
print('='*30)
print("Thank you for shopping here, have a great day ")
print('='*30)
but i get an error line 95, in
print ("Item: %s. Price: %s") % (option, prices[option])
KeyError: 1
any solution or better ways to improve the code would be really great
Try using F-Strings. They let you format text far more easily. Here's an example.
x = "hello!"
print(f"shr4pnel says {x}")
>>> shr4pnel says hello!
The problem in this case is that option == 1. 1 isn't a key in the dictionary so nothing is output. Hope this helps. This is because the dictionary does not have 1 as a key. To access the item the dictionary would have to be formatted like this.
prices = {1: "burger", 2: "hot dog"}
print(prices[1])
>>> burger

How to add unknown values in python

I am trying to create a cash register program. My objective is for all the products be added and the final price be found. How can I reach this goal without knowing the values previously? Below is my code. Thanks in advance for any help it is greatly appreciated
responses = {}
polling_active = True
print("Welcome to the cash register. Insert your product name and price to be able to calculate your final total")
total = 0
while polling_active:
product = input("\nProduct Name: ")
total += float(input("Price: "))
responses[product] = total
repeat = input("Is this your final checkout? (Yes/No)")
if repeat == 'no':
polling_active = True
elif repeat == 'No':
polling_active = True
elif repeat == 'Yes':
polling_active = False
elif repeat == 'yes':
polling_active = False
else:
print("That operation is invalid")
print("\n---Final Checkout---")
for product, price in responses.items():
print(product + " is $" + str(total))
print("\n---Total Price---")
print("Store Price is: ")
print("$" + str(total))
print("\n---Tax Price---")
print("Your price with tax is: ")
total = total * 1.13
print("$" + "{0:.2f}".format(float(total)))
print("\nThank you for shopping with us! Have a great day!")
I understand the with my current code, total will not allow me to add any products but that is just currently a place holder
Here is the code that you need:
responses = {}
polling_active = True
print("Welcome to the cash register. Insert your product name and price to be able to calculate your final total")
while polling_active:
product = input("\nProduct Name: ")
price = float(input("Price: "))
responses[str(product)] = price
repeat = raw_input("Is this your final checkout? (Yes/No)")
if repeat.lower() == 'no':
polling_active = True
elif repeat.lower() == 'yes':
polling_active = False
else:
print("That operation is invalid")
print("\n---Final Checkout---")
for product, price in responses.items():
print(product + " is $" + str(price))
print("\n---Total Price---")
print("Store Price is: ")
total= sum(responses.values())
print("$" + str(total))
print("\n---Tax Price---")
print("Your price with tax is: ")
total = total * 1.13
print("$" + "{0:.2f}".format(float(total)))
print("\nThank you for shopping with us! Have a great day!")
Output:
integer:
float:

Im tring to make a BMI BMR calculator in Pythion3

well i am trying to make a bmi & bmr calculator.
I have got the code down yet when i select bmi, it goes through the bmi process then immediately after it has finished it runs the mbr, then the program crashes?
HALP?
#menu
#Ask weather to print BMI or BMR
output = str(input('Calulate BMI or BMR or Exit: '))
print (output)
#BMI
if output == 'BMI' or 'bmi':
#Get height and weight values
height = int(input('Please enter your height in inches: '))
weight = int(input('Please enter your weight in pounds: '))
#Do the first steps of the formula
heightSquared = (height * height)
finalWeight = (weight * 703)
#Fiqure out and print the BMI
bmi = finalWeight / heightSquared
if bmi < 18:
text = 'Underweight'
if bmi <= 24: # we already know that bmi is >=18
text = 'Ideal'
if bmi <= 29:
text = 'Overweight'
if bmi <= 39:
text = 'Obese'
else:
text = 'Extremely Obese'
print ('Your BMI is: ' + str(bmi))
print ('This is: ' + text)
#bmr
if output == 'bmr' or 'BMR':
gender = input('Are you male (M) or female (F) ')
if gender == 'M' or 'm':
#Get user's height, weight and age values.
height = int(input('Please enter your height in inches'))
weight = int(input('Please enter your weight in pounds'))
age = int(input('Please enter your age in years'))
#Figure out and print the BmR
bmr = 66 + (6.2 * weight) + (12.7 * height) - (6.76 * age)
print (bmr)
if gender == 'F' or 'f':
#Get user's height, weight and age values.
height = int(input('Please enter your height in inches'))
weight = int(input('Please enter your weight in pounds'))
age = int(input('Please enter your age in years'))
#Figure out and print the BmR
bmr = 655 + (4.35 * weight) + (4.7 * height) - (4.7 * age)
print (bmr)
#exit
elif output == 'exit' or 'Exit' or 'EXIT':
exit()
Any help is welcome!
Cheers!
There are many bugs or inconsistencies within your code, here are a few main ones.
The or logical operator cannot be used like that, this is most prominent in the main if statements. Here is a tutorial to get you started on that.
The if and elif are very badly used, if is for a condition, elif is run if the subsequent if hasn't been satisfied, and if the code within the elif has, while the third one, else is more of a default statement, per se, if nothing was satisfied go to this one. Here is some documentation about it.
You are reusing the same code way too much, this should be fixed.
There are a few other tidbits that will show themselves in the code below, I've heavily commented the code so you can understand it thoroughly.
# Menu
# Ask whether to print BMI, BMR, or to exit
output = str(input('Calulate BMI or BMR or Exit: '))
print ('You entered: ' + output) # Try not to print 'random' info
# Exit, I put it up here to make sure the next step doesn't trigger
if output == 'exit' or output == 'Exit' or output == 'EXIT':
print('Exiting...') # Try to always notify the user about what is going on
exit()
# Check if the input is valid
if output != 'BMI' and output != 'bmi' and output != 'BMR' and output != 'bmr':
print('Please enter a valid choice.')
exit()
# Get user's height, weight and age values
# Never write code more than once, either place it in a function or
# take it elsewhere where it will be used once only
height = int(input('Please enter your height in inches: '))
weight = int(input('Please enter your weight in pounds: '))
# BMI
if output == 'BMI' or output == 'bmi':
# Do the first steps of the formula
heightSquared = (height * height)
finalWeight = (weight * 703)
# Figure out and print the BMI
bmi = finalWeight / heightSquared
if bmi < 18: # First step, is it less than 18?
text = 'Underweight'
elif bmi <= 24: # If it isn't is it less than or equal to 24?
text = 'Ideal'
elif bmi <= 29: # If not is it less than or equal to 29?
text = 'Overweight'
elif bmi <= 39: # If not is it less than or equal to 39?
text = 'Obese'
else: # If none of the above work, i.e. it is greater than 39, do this.
text = 'Extremely Obese'
print ('Your BMI is: ' + str(bmi))
print ('This is: ' + text)
# BMR
elif output == 'bmr' or output == 'BMR':
gender = str(input('Are you male (M) or female (F): '))
age = int(input('Please enter your age in years: '))
bmr = 0 # Initialize the bmr
if gender == 'M' or gender == 'm':
# Figure out and print the BMR
bmr = 66 + (6.2 * weight) + (12.7 * height) - (6.76 * age)
if gender == 'F' or gender == 'f':
# Figure out and print the BMR
bmr = 655 + (4.35 * weight) + (4.7 * height) - (4.7 * age)
print ('Your BMR is: ' + bmr)

Python: Unknown Syntax Error (easy)

I'm getting a syntax error around the word rental and I just have no clue what I've done wrong. This is like my 6th program. Any and all suggestions are helpful.
#Computes Cable Bill
print("Welcome to cable customer billing calculator")
acct = int(input("Enter an account number"))
cust_type = input("Enter customer type: (R) Residential or (B) Business: ")
def residential():
processing = 4.50
basic_service = 20.50
daily_rental = 2.99
prem_channel_fee = 7.50
prem_channels = int(input("Enter the number of premium channels used: ")
rental = int(input("Were movies rented (Y or N): ")
if rental == Y or y:
rental_days = int(input("Enter the total number of rental days (one day for each movie, each day): ")
else:
rental_days = 0
bill_amt = processing + basic_service + (rental_days * daily_rental) + (prem_channels * prem_channel_fee)
return (bill_amt)
def business():
processing = 15
basic_service = 75
prem_channel_fee = 50
connections = int(input("Enter the number of basic service connections: ")
prem_channels = int(input("Enter the number of premium channels used: ")
if (connections <= 10):
bill_amt = processing + basic_service + (prem_channel * prem_channel_fee)
else:
bill_amt = processing + basic_service + ((connections - 10) * 5) + (prem_channel * prem_channel_fee)
return (bill_amt)
if (cust_type == "R" or "r"):
bill_total = residential()
else:
bill_total = business()
print("Account number: ", acct)
print("Amount due: ",bill_total)
You need to add closing parentheses as depicted in the snippet below and ensure that the first line of your conditionals line up with the previous line. Also, consider matching the value of rental against a list of valid responses – it's more Pythonic way of writing the logic you're proposing:
prem_channels = int(input("Enter the number of premium channels used: "))
rental = int(input("Were movies rented (Y or N): "))
if rental in ['Y', 'y']:
rental_days = input("Enter the total number of rental days (one day for each movie, each day): ")
Similarly, the following lines need closing parentheses:
connections = int(input("Enter the number of basic service connections: "))
prem_channels = int(input("Enter the number of premium channels used: "))
Replace the logic of your final conditional as above:
if (cust_type in ["R", "r"]):
Or, alternatively (but less Pythonic):
if (cust_type == "R" or cust_type == "r"):
Finally, note that input("Were movies rented (Y or N): ") returns a string and thus should not be cast to an integer. If you cast it using int(), you'll receive a type error and if rental in ['Y', 'y']: will never evaluate to true.
if rental == 'Y' or rental == 'y':
Should solve this
Following should help you.
rental = str(input("Were movies rented (Y or N): "))
if rental == "Y" or rental == "y":
Points raised by zeantsoi are also valid. Please consider them too.
There are a number of errors:
prem_channels = int(input("Enter the number of premium channels used: ") needs closing parenthesis.
rental = int(input("Were movies rented (Y or N): ") remove int(. The input is a string.
if rental == Y or y: should be if rental == 'Y' or rental == 'y':.
The whole if rental block needs unindented to line up with the previous line.
The two lines below need trailing ):
connections = int(input("Enter the number of basic service connections: ")
prem_channels = int(input("Enter the number of premium channels used: ")
The if (connections block needs unindented to line up with the previous line.
if (cust_type == "R" or "r"): should be if cust_type == 'R' or cust_type == 'r':
The bill_amt calculations both need to use prem_channels not prem_channel.
In addition, parentheses around if statements and return values are unnecessary.
Here's your code with the above fixes:
#Computes Cable Bill
print("Welcome to cable customer billing calculator")
acct = int(input("Enter an account number"))
cust_type = input("Enter customer type: (R) Residential or (B) Business: ")
def residential():
processing = 4.50
basic_service = 20.50
daily_rental = 2.99
prem_channel_fee = 7.50
prem_channels = int(input("Enter the number of premium channels used: "))
rental = input("Were movies rented (Y or N): ")
if rental == 'Y' or rental == 'y':
rental_days = int(input("Enter the total number of rental days (one day for each movie, each day): "))
else:
rental_days = 0
bill_amt = processing + basic_service + (rental_days * daily_rental) + (prem_channels * prem_channel_fee)
return bill_amt
def business():
processing = 15
basic_service = 75
prem_channel_fee = 50
connections = int(input("Enter the number of basic service connections: "))
prem_channels = int(input("Enter the number of premium channels used: "))
if connections <= 10:
bill_amt = processing + basic_service + (prem_channels * prem_channel_fee)
else:
bill_amt = processing + basic_service + ((connections - 10) * 5) + (prem_channels * prem_channel_fee)
return bill_amt
if cust_type == "R" or cust_type == "r":
bill_total = residential()
else:
bill_total = business()
print("Account number: ", acct)
print("Amount due: ",bill_total)

Categories