Pounds and Ounces in Python - python

I just started to learn coding and I'm having an issue trying to get the pounds converted over to ounces. We're suppose to allow the user to input their data like 6 pounds 2 ounces. I'm stuck at the moment and I'm not even sure if I'm going about this right. Any help would be appreciated.
Your program will accept as input the weights in pounds and ounces for a set of rabbits fed with one type of food. Let the user provide the name of food. Accept input until the user types a zero weight. Make life easier by converting weights to ounces. Compute the arithmetic mean (average) of each set of rabbits. Determine which set of rabbits weighs the most, reporting their average weight.
This was my orignal code before using pounds and ounces and it worked fine using simple number like 13.
f1 = input("Name of Food:")
print (f1)
counter = 0
sum = 0
question = input('''Enter a weight? Type "Yes" or "No" \n\n''')
while question == "Yes" :
ent_num = int(input("Weight of Rabbit:"))
sum = sum + ent_num
counter = counter + 1
question = input('''Enter another weight? Type "Yes" or "No". \n ''')
print ("Average weight " + str(sum/counter))
My current code looks like this after I tried to implement pounds and ounces into the input.
f1 = input("Name of Food: ")
print (f1)
counter = 0
sum = 0
print ("Please enter inforamtion in pounds and ounces. End")
question = input('''Enter a weight? Type "Yes" or "No" \n\n''')
while question == "Yes" :
ent_num = int(input("Weight of Rabbit:"))
sum = sum + ent_num
counter = counter + 1
if pounds * ounces == 0:
allOunces = pounds * 16 + ounces
sum = sum + allOunces
print ("Average weight " + str(sum/counter))

A big part of programming is learning how to cleanly break a big problem into smaller pieces.
Let's start by getting a single weight:
POUND_WORDS = {"pound", "pounds", "lb", "lbs"}
OUNCE_WORDS = {"ounce", "ounces", "oz", "ozs"}
OUNCES_PER_POUND = 16
def is_float(s):
"""
Return True if the string can be parsed as a floating value, else False
"""
try:
float(s)
return True
except ValueError:
return False
def get_weight(prompt):
"""
Prompt for a weight in pounds and ounces
Return the weight in ounces
"""
# We will recognize the following formats:
# 12 lb # assume 0 ounces
# 42 oz # assume 0 pounds
# 12 6 # pounds and ounces are implied
# 3 lbs 5 oz # fully specified
# repeat until we get input we recognize
good_input = False
while not good_input:
# get input, chunked into words
inp = input(prompt).lower().split()
if len(inp) not in {2, 4}:
# we only recognize 2-word or 4-word formats
continue # start the while loop over again
if not is_float(inp[0]):
# we only recognize formats that begin with a number
continue
# get the first number
v1 = float(inp[0])
if len(inp) == 2:
if inp[1] in POUND_WORDS:
# first input format
lbs = v1
ozs = 0
good_input = True
elif inp[1] in OUNCE_WORDS:
# second input format
lbs = 0
ozs = v1
good_input = True
elif is_float(inp[1]):
# third input format
lbs = v1
ozs = float(inp[1])
good_input = True
else:
# 4 words
if inp[1] in POUND_WORDS and is_float(inp[2]) and inp[3] in OUNCE_WORDS:
lbs = v1
ozs = float(inp[2])
good_input = True
return lbs * OUNCES_PER_POUND + ozs
Now we can use that to get the average of a bunch of weights:
def get_average_weight(prompt):
"""
Prompt for a series of weights,
Return the average
"""
weights = []
while True:
wt = get_weight(prompt)
if wt:
weights.append(wt)
else:
break
return sum(weights) / len(weights)
Now we want to get the average for each food type:
def main():
# get average weight for each feed type
food_avg = {}
while True:
food = input("\nFood name (just hit Enter to quit): ").strip()
if food:
avg = get_average_weight("Rabbit weight in lbs and ozs (enter 0 0 to quit): ")
food_avg[food] = avg
else:
break
# now we want to print the results, sorted from highest average weight
# Note: the result is a list of tuples, not a dict
food_avg = sorted(food_avg.items(), key = lambda fw: fw[1], reverse=True)
# and print the result
for food, avg in food_avg:
lbs = int(avg // 16)
ozs = avg % 16
print("{:<20s} {} lb {:0.1f} oz".format(food, lbs, ozs))
and then run it:
main()
This still takes some fussing around to get the average weight to print properly - our program needs to "know about" how weights are represented. The next step would be to push this back into a Weight class - ideally one which is agnostic about weight units (ie can accept arbitrary units like kilograms or pounds or stone).

You need to save the pounds and ounces in separate variable so something like this is needed.
f1 = input("Name of Food: ")
print (f1)
counter = 0
sum = 0
print ("Please enter inforamtion in pounds and ounces. End")
question = input('''Enter a weight? Type "Yes" or "No" \n\n''')
while question == "Yes" :
pounds, ounces = map(int, input().split())
weight = pounds * 16 + ounces
sum = sum + weight
counter = counter + 1
if pounds * ounces == 0:
print ("Average weight " + str(sum/counter))

There are a few issues with the second block of code.
1.
question = input('''Enter a weight? Type "Yes" or "No" \n\n''')
while question == "Yes" :
...
You need to ask your question inside the loop. You will loop endlessly because they never get asked to change question again inside the loop. What I would do is set question = "Yes" before the loop and then have the first line inside your loop be
question = input('''Enter a weight? Type "Yes" or "No" \n\n''')
2.
You need to decide how you want the user to enter input. You currently have
ent_num = int(input("Weight of Rabbit:"))
But ent_num could be anything from "6lbs 12oz" to "7pounds11ounces" to "potato". There's no consistent way to parse it unless you specifically tell them how to type out the weight. A less ambiguous way to ask this would be to say something like:
raw_input = input("Please enter the weight of the rabbit in pounds
and ounces with a space separating the two numbers (e.g. 7lbs 12oz):")
Then you can do something to recover the two separate numbers. Something like this should work.
#split the string by the space.
chunked_input = raw_input.split()
#get the digits in the two chunks
lbs, ounces = map(lambda x: int(filter(str.isdigit, x)), chunked_input)
Now that bit probably requires a bit of explanation. map here is taking a function (the lambda x bit) and applying that function to all the members of chunked_input. map(lambda x: x+2, [4, 6, 7]) == [6, 8, 9].
Lambdas are just a tool to make a quick function without having to name it. You could accomplish the same thing as the lbs, ounces line by writing your own function:
def get_digit(my_substring):
return int(filter(str.isdigit, my_substring)
and then mapping it:
lbs, ounces = map(get_digit, chunked_input)
Regardless, once you have the lbs and ounces as two separate variables, you're good to go. You can normalize them with the same formula you used:
weight = pounds * 16 + ounces
And then you'll eventually have the total weight in ounces of every weight entered.
To print out the average weight at the end you can do the division the way you did before:
#the * 1.0 is because if you can have fractional results, one of
#either the divisor or the dividend must be a float
avg_oz_weight = sum * 1.0/counter
and then if you want to display it in lbs and ounces, you need two useful operators, % and //. % is called the modulo operator, it returns the remainder when you're doing division so (7 % 3 == 1, 6 % 2 == 0). The // operator is floor division, so (7 // 3 == 2, 6 // 2 == 3).
So you can print a nice result with:
print("The average weight is: {}lbs {}oz".format(avg_oz_weight // 16,
avg_oz_weight % 16))

Related

What is the function for Varied amount input data for Python?

Statistics are often calculated with varying amounts of input data. Write a program that takes any number of integers as input, and outputs the average and max.
Ex: If the input is:
15 20 0 5
the output is:
10 20
nums = []
# initialse
number = 0
# loop until there isn't an input
while number != "":
# ask for user input
number = input('Enter number:')
# validate the input isn't blank
# prevents errors
if number != "":
# make input integer and add it to list
nums.append(int(number))
avg = sum(nums) / len(nums)
print(max(nums), avg)
All is gives me is Enter number:
I solved the problem correctly using this:
user_input = input()
tokens = user_input.split() # Split into separate strings
nums = []
for token in tokens: # Convert strings to integers
nums.append(int(token))
avg = sum(nums) / len(nums) # Calculates average of all integers in nums
print(int(avg), max(nums)) # Prints avg as an Integer instead of a Float
nums = []
# loop until there isn't an input
while not nums:
# ask for user input
number = input()
nums = [int(x) for x in number.split() if x]
avg = int(sum(nums) / len(nums))
print(avg, max(nums))
Zybooks
9.16 LAB: Varied amount of input data
user_input = input().split(" ")
average = 0.00
for x in range(len(user_input)):
average += float(user_input[x])
user_input[x] = float(user_input[x])
average = float(average) / len(user_input)
print(f'{max(user_input):.2f} {round(average,2):.2f}')

How to create a shopping cart calculator

I am writing a program which takes one input (a number of product) and gives one output (price of the product):
Drink: $2.25
6-pack: $10
25% discount if more than $20
((Sorry if my code is really bad I'm a newbie))
print( "How many drinks do you want?" )
drinks = input( "Enter number: ")
total = int(drinks)
single = 2.25
six = 10
single * 6 = six
if total > 20:
total * 0.75
print( "That will be a total of: ", total, "dollars")
I'm confused how to make it so that, after I have changed the input value to an int, how can I separate and calculate it based on my pricing criteria. Please help?
I assume you're looking for something like this. Hope it helps! I tried to keep your variable names the same so it would make some kind of sense to you. The line I commented out is an error.
drinks = input("How many drinks do you want?")
drinks = int(drinks)
total = 0
single = 2.25
six = 10
sixPacks = drinks // 6
singles = drinks % 6
# single * 6 = six
total += six * sixPacks
total += single * singles
if total > 20:
total *= 0.75
print( "That will be a total of: {} dollars".format(round(total, 2)))
Okay so let's break it down logically.
You first take in the input number of drinks the person wants. You're assigning it to total right away, when you should actually assign it to a variable that holds the number of drinks.
You should then multiply the number of drinks by the cost per drink. You also need to check if the number of drinks are a multiple of 6 so that you can price them by the six pack.
Once you have calculated this check if the total < 20.
Since this is a homework problem. I will encourage you to try to solve it with this approach.

How do I find grams of a compound if I have Molar Mass in Python?

I'm having some difficulty trying to convert from Molar Mass back to grams. This program spits out Molar Mass of Compound A at x grams(user input).
If I have 10grams of SiO2, then how much grams(respectfully), is Si and O2?
How would I code the user's input of let's say 10g SiO2 and convert it to how much needed g of Si and g of O?
10gSiO2 / M SiO2 * MSi = gSi
2*(10g SiO2 / M SiO2) * MO = gO (multiply by 2 because O2)
M = Molar Mass
g = grams
m = mole
import Periodic_Table_new as pt
print("Enter info for Compound A\n")
compoundA = pt.getInput()
gramTotal = float(input("Please enter total grams of Compound A: "))
moles = pt.convertToMoles(gramTotal,compoundA)
moleMass = moles/compoundA
print('\n')
print("The Molecular Mass of compound A at " + str(gramTotal) + "grams is : " + str(moleMass) + "\n\n")
Periodic_Table_new.py
def getInput():
compoundName = ""
ix = True
total = 0
while ix:
elementName = str(input("Please Enter Element: "))
amountNum = int(input("Please Enter Amount of Element: "))
elementWeight = float(input("Please enter Element Weight: "))
elementWeight = amountNum * elementWeight
total = total + elementWeight
compoundName = compoundName + elementName + str(amountNum)
print(compoundName)
userInput = input("Would you like to repeate? \n Y/N? ")
if userInput == 'N' or userInput == 'n':
ix = False
print(compoundName)
print(total)
return total
def convertToMoles(gOc,c):
moles = gOc/c
return moles
def molesToGrams():
p = moles * n * m
I came up with a little bit of a different approach, based on my understanding of your desired results. This version is going to use a dictionary of atomic masses, regex to parse the compound string, and a loop to do the math. It's pretty flexible, but it requires you to build the dictionary of atomic masses, which shouldn't be hard, just a little tedious. It has some requirements for the input noted in the comments
import re
atomic_masses = {'Si': 28.0855, 'O': 15.999}
compound = input('Please enter a compound and amount: ')
amount_pat = re.compile(r'(\d+)g') # compound mass must end in the letter g
element_pat = re.compile(r'([A-Z][a-z]?\d*)') # elemental symbols must be properly capitalized (Si, not si)
sym_pat = re.compile(r'[A-Z][a-z]?') # elemental symbols must be properly capitalized (Si, not si)
qty_pat = re.compile(r'\d+')
mass = int(amount_pat.search(compound)[1])
elements = []
# finds each element in the compound and makes a list of (element, parts) tuples
for element in element_pat.finditer(compound):
element = element[0]
symbol = sym_pat.search(element)[0]
if any(c.isdigit() for c in element):
qty = int(qty_pat.search(element)[0])
else:
qty = 1
elements.append((symbol, qty))
# Calculates and prints total Molecular Mass for the compund
molecular_mass = sum(el[1] * atomic_masses[el[0]] for el in elements)
print(f'\nTotal Molecular Mass: {molecular_mass}\n')
# Calculates and prints the mass for each element
for tup in elements:
unit_mass = (mass / molecular_mass) * atomic_masses[tup[0]] * tup[1]
print(f'{tup[0]}: {unit_mass:.4f}g')
Example Output:
Please enter a compound and amount: 10g SiO2
Total Molecular Mass: 60.0835
Si: 4.6744g
O: 5.3256g
Edit:
In order to accommodate decimal mass for the input, we can change the regex inside amount_pat to r'(\d*.\d+)g'. Now it will accept values such as .003g or 0.003g. It still does not take kg or mg, but if you lookup the built-in re package, you can get an idea how regex works and change it from there. regex101 is also a good resource for regex, since it allows a trial and error approach to learning. I also changed int to float in the mass assignment statement
I did, however, change the elemental mass loop to adjust for mg and kg. If you wish to expand it further, just take the pattern I've started here and expand it further:
for tup in elements:
unit_mass = (mass / molecular_mass) * atomic_masses[tup[0]] * tup[1]
if unit_mass > 1000:
unit_mass /= 1000
unit = 'kg'
elif unit_mass < .01:
unit_mass *= 1000
unit = 'mg'
else:
unit = 'g'
print(f'{tup[0]}: {unit_mass:.4f}{unit}')
New Example Output:
Please enter a compound and amount: .003g H2O
Total Molecular Mass: 18.01488
H: 0.3357mg
O: 2.6643mg
You will need the elements at the end, that is the missing part.
Without the input magic, here is an example for 10g SiO2:
target=10
elem=[['Si',1,28.09],['O',2,16]]
total=0
for e in elem:
total=total+e[1]*e[2]
print('molar mass of compound:',total)
moles=target/total
print('moles:',moles)
for e in elem:
print(e[0],moles*e[1],'mol',moles*e[1]*e[2],'g')
Computing the Molar Mass and Mass Percentage of Elements within a Compound
I used the pyvalem package to achieve your desired output.
Here is my code
from pyvalem.formula import Formula
import numpy as np
def give_compound_details(compound, given_gram):
# Dictionary of element of mole of a compound
ele_mol_dict = Formula(compound).atom_stoich
# Create a list comprehensioon to get the mass per ele
mass_per_ele = [Formula(ele).mass * ele_mol_dict[ele] for ele in ele_mol_dict.keys()]
# Create dic for ele and mass
ele_mass_dict = dict(zip(list(Formula(compound).atom_stoich),mass_per_ele))
# Create a list comprehension and dictionary for mass percentage per element of a compound
ele_percent_mass_dict = dict(zip(list(ele_mol_dict.keys()),[(ele_mass_dict[ele] / Formula(compound).mass * 100) for ele in ele_mass_dict.keys()]))
print(f"Total Molecular mass of {compound}: {Formula(compound).mass} g\n")
for key, value in ele_mass_dict.items():
print(f"Molar Mass of {key}: {value} g")
print("")
for key, value in ele_percent_mass_dict.items():
print(f"Mass Percentage of {key}: {round(value,2)} %")
print("")
print(f"If molecular mass of {compound} is {given_gram} g, therefore")
for key, value in ele_percent_mass_dict.items():
print(f"Mass of {key}: {round((value/100)*given_gram,4)} g")
# MAIN PROGRAM
is_running = True
while is_running:
print("Computing the Molar Mass and Mass Percentage of Elements within a Compound")
print("")
compound = input("Compound: ")
given_gram = float(input(f"How much {compound} do you have in grams? "))
print("\nRESULT\n")
function = give_compound_details(compound, given_gram)
print("---------------------------------------")
ask = input('Do you want to try again? \nType "y" is YES, type "n" if NO')
if ask.islower() == 'n':
is_running = False
print("---------------------------------------")
Here is the sample output:
Screenshot of the output

Python 3 - Getting multiple inputs for a variable

I'm trying to get the user to be able to input several values into the cash register. When they are done, all they have to type in is -1 and it won't request any more values to be input. Once this is done, the program adds up the total of the numbers input, and then spits them out in a message as netPrice. grossPrice however adds them up but adds 10% GST to the end value. I've had no experience with raw_input or continuing variables, and searching here I found some information that I attempted to apply to the code, however failed for me.
#x = continued input ("Enter in net price of items for the cash register: ")
#if x -1:
# stop;
#netPrice = x
#grossPrice = netPrice + (0.1 * netPrice)
#print ("The net price of all items is: $",netPrice)
#print ("The gross price of all items (this includes GST) is: $",grossPrice)
x = raw_input("Enter in net price of items for the cash register: ")
if x >=-1:
stop;
netPrice = x
grossPrice = netPrice + (0.1 * netPrice)
print ("The net price of all items is: $",netPrice)
print ("The gross price of all items (this includes GST) is: $",grossPrice)
You can do something as follows:
values = []
while True:
x = float(input('Enter in net price of items for the cash register: '))
if x == -1:
break
values.append(x)
print ("The net price of all items is: " + str(sum(values)))

How do I get the sum of all numbers in a range function in Python?

I can't figure out how to take x (from code below) and add it to itself to get the sum and then divide it by the number of ratings. The example given in class was 4 ratings, with the numbers being 3,4,1,and 2. The average rating should be 2.5, but I can't seem to get it right!
number_of_ratings = eval(input("Enter the number of difficulty ratings as a positive integer: ")) # Get number of difficulty ratings
for i in range(number_of_ratings): # For each diffuculty rating
x = eval(input("Enter the difficulty rating as a positive integer: ")) # Get next difficulty rating
average = x/number_of_ratings
print("The average diffuculty rating is: ", average)
Your code doesn't add anything, it just overwrites x in each iteration. Adding something to a variable can be done with the += operator. Also, don't use eval:
number_of_ratings = int(input("Enter the number of difficulty ratings as a positive integer: "))
x = 0
for i in range(number_of_ratings):
x += int(input("Enter the difficulty rating as a positive integer: "))
average = x/number_of_ratings
print("The average diffuculty rating is: ", average)
try:
inp = raw_input
except NameError:
inp = input
_sum = 0.0
_num = 0
while True:
val = float(inp("Enter difficulty rating (-1 to exit): "))
if val==-1.0:
break
else:
_sum += val
_num += 1
if _num:
print "The average is {0:0.3f}".format(_sum/_num)
else:
print "No values, no average possible!"

Categories