Celsius to Fahrenheit loop in list - python-3.x

I'm trying to create a list of Celsius to Fahrenheit temperature conversions from celsius range 0-100 in increments of 0.5. This is what I have so far but I can't seem to get the loop to run correctly because it starts with celsius:0 fahrenheit:0; I need it to start with celsius:0 fahrenheit:32 (the correct conversion).
count = 0
celsius = 0
while (celsius <= 100):
print ('Celsius:', celsius, 'Fahrenheit:', count)
celsius = celsius + 0.5
count = (((celsius)*9/5)+32)

I think what you're looking for is more something like this:
celsius = 0
while celsius <= 100:
fahrenheit = celsius * 9.0/5.0 + 32
print ('Celsius:', celsius, 'Fahrenheit:', fahrenheit)
celsius += 0.5

Why don't you write a function?
def toFarenheit(celsius):
return (9.0/5.0) * celsius + 32
def toCelsius(farenheit):
return (farenheit - 32) * (5.0 / 9.0)
# I don't actually use this method, but it's still good to have
Then, you can do:
for y in range(0,200):
x = y / 2.0
print("Celsius: ", x, ", Farenheit: ", toFarenheit(x))

Related

How can I use input function to fill the parameters?

Create a function called computepay which takes two parameters (hours and rate ).
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
This is my code, but it doesn't show an input dialog when I run the program.
def computepay(x, y):
x = input('Enter Hours: ')
y = input('Enter Rate: ')
if int(x) <= 40 :
print('\nPay: ' + int(x) * int(y))
else :
print('\nPay: ' + 40 * int(y) + ((int(x) - 40) * 15))
If you want to just call the function with zero or empty string or even you can pre define in it, now you can get the input dialog in whatever ide you are using
def computepay(x=0, y=0):
x = input('Enter Hours: ')
y = input('Enter Rate: ')
if int(x) <= 40 :
print('\nPay: ' + str(int(x) * int(y)))
else :
print('\nPay: ' +str( 40 * int(y) + ((int(x) - 40) * 15)))
computepay()
Do like this and let me know if that works out for you Dale
def computepay():
x = int(input('Enter Hours: ')) #this is the way to get int input
y = int(input('Enter Rate: '))
if x <= 40 :
basicCompute = x * y
#use f-string instead, it is clean and correct, the way you were doing things with the print was wrong
print(f'\nPay: {basicCompute}')
else :
# have a variable which computes that for you, don't do that in your print directly
compute = (40 * y) + ((x - 40) * 15)
print(f'\nPay: {compute}')
# this is how you call your method
computepay()
OUTPUT
# this is how you get the thing in your terminal, tested and verified
Enter Hours: 30
Enter Rate: 10
Pay: 300
ALTERNATIVE
If you want your method to accept the two arguments, then do not do input() inside your method
def computepay(x, y):
# use x and ye with the arguments only
if x <= 40 :
basicCompute = x * y
print(f'\nPay: {basicCompute}')
else :
compute = (40 * y) + ((x - 40) * 15)
print(f'\nPay: {compute}')
# When you call your method, before that you have to accept x and y params, then
# pass it to your method
hours = int(input('Enter Hours: '))
rate = int(input('Enter Rate: '))
# then pass it to your method
# this will do the call, and print the data in your console
computepay(hours, rate)
Hope that helps :)
You need to call that function below.
computepay(parameterA,parameterB)
Mind the indentation issues!

Why PulP returns negative values for blending problem while the lowBound is set to zero?

I am using Python PulP to solve blending problem. The output is weird it returns negative values. What I am trying to
from pulp import *
import pandas as pd
data = pd.read_csv('feed.csv')
# Get required data from user
Ingredients = ['CORN', 'SBM', 'LIMESTONE', 'SALT', 'BONE_MEAL', 'PALM_OIL']
def cost():
costs = {}
for i in Ingredients:
costs[i] = data.loc[data['feed'] == i, 'cost'].iloc[0]
return costs
def protein():
proteinPercent = {}
for i in Ingredients:
proteinPercent[i] = data.loc[data['feed'] == i, 'protein'].iloc[0]
return proteinPercent
def energy():
energyKcal = {}
for i in Ingredients:
energyKcal[i] = data.loc[data['feed'] == i, 'energy'].iloc[0]
return energyKcal
def calcium():
cal = {}
for i in Ingredients:
cal[i] = data.loc[data['feed'] == i, 'calcium'].iloc[0]
return cal
def sodium():
sod = {}
for i in Ingredients:
sod[i] = data.loc[data['feed'] == i, 'sodium'].iloc[0]
return sod
def minimum():
min = {}
for i in Ingredients:
min[i] = data.loc[data['feed'] == i, 'min'].iloc[0]
return min
def maximum():
max = {}
for i in Ingredients:
max[i] = data.loc[data['feed'] == i, 'max'].iloc[0]
return max
# Initialize
costs = cost()
proteinPercent = protein()
energyKcal = energy()
cal = calcium()
sod = sodium()
L = minimum()
U = maximum()
# Create the 'prob' variable to contain the problem data
prob = LpProblem("Broiler Ration Formulation", LpMinimize)
# A dictionary called 'ingredient_vars' is created to contain the referenced Variables
ingredient_vars = LpVariable.dicts("Ingr",Ingredients, lowBound = 1, upBound = 60)
for i in Ingredients:
prob += ingredient_vars[i] >= L[i]
prob += ingredient_vars[i] <= U[i]
# The objective function is added to 'prob' first
prob += lpSum([costs[i]*ingredient_vars[i] for i in Ingredients]), "Total Cost of Ingredients per can"
# The five constraints are added to 'prob'
prob += lpSum([ingredient_vars[i] for i in Ingredients]) == 100, "Percentages Sum"
prob += lpSum([proteinPercent[i] * ingredient_vars[i] for i in Ingredients]) >= 19.0, "Min Protein Requirement"
prob += lpSum([proteinPercent[i] * ingredient_vars[i] for i in Ingredients]) <= 21.0, "Max Protein Requirement"
prob += lpSum([energyKcal[i] * ingredient_vars[i] for i in Ingredients]) >= 3100.0, "Min Energy Requirements"
prob += lpSum([energyKcal[i] * ingredient_vars[i] for i in Ingredients]) <= 3300.0, "Max Energy Requirements"
prob += lpSum([cal[i] * ingredient_vars[i] for i in Ingredients]) <= 1.1, "Calcium Requirements"
prob += lpSum([sod[i] * ingredient_vars[i] for i in Ingredients]) <= 0.2, "Sodium Requirements"
# The problem is solved using PuLP's choice of Solver
prob.solve()
# The status of the solution is printed to the screen
print("Status:", LpStatus[prob.status])
# Each of the variables is printed with it's resolved optimum value
for v in prob.variables():
print (v.name, "=", v.varValue)
# The optimised objective function value is printed to the screen
print ("Total Cost of Ingredients per feed= ", value(prob.objective))
File feed.csv content
feed min max cost energy protein calcium sodium
BONE_MEAL 0 10 0.7 1600 0 30.32 1
CORN 0 60 0.5 3350 9.4 0.05 0
.
.
.
Some of the ouput variables are negatives:
Status: Infeasible
Ingr_BONE_MEAL = 1.0
Ingr_CORN = 37.862563
Ingr_FISH_MEAL = 1.0
Ingr_LIMESTONE = -0.81506256
Ingr_PALM_OIL = 60.0
Ingr_SALT = -0.0475
Ingr_SBM = 1.0
Total Cost of Ingredients per Feed = 32.988153372
I searched for possible solution but could not find any explanation or maybe my code wrong but cant figure out what went exactly went wrong.
The first thing you add to you LpProblem instance will always be the objective function as described in the PuLP documentation. The order you have currently in your code is:
for i in Ingredients:
prob += ingredient_vars[i] >= L[i]
prob += ingredient_vars[i] <= U[i]
# The objective function is added to 'prob' first
prob += lpSum([costs[i]*ingredient_vars[i] for i in Ingredients]), "Total Cost of Ingredients per can"
Your problem instance's objective function is ingredient_vars[i] >= L[i] which is non sensical.
The correct way is to add the objective function part before your constraints ,like so:
# The objective function is added to 'prob' first
prob += lpSum([costs[i]*ingredient_vars[i] for i in Ingredients]), "Total Cost of Ingredients per can"
for i in Ingredients:
prob += ingredient_vars[i] >= L[i]
prob += ingredient_vars[i] <= U[i]
a good way to do the debugging of your linear program is to use the prob.writeLP('blendingprob') method which writes out an .lp file that shows the actual linear program
This can happen when you have an Infeasible solution, which is what you have here. Since the solution is infeasible, pulp just throws out a solution, under which some of the constraints may be violated. You need to find out which of your constraints is incompatible with the others and change them. Perhaps you need to widen your calorie range, for instance.

None as a output to my code. I wanted a calculated output from my code. Is it wrong to use logical statement after if else?

I am working on a project and my code is returning none as output
I have tried indenting and unindenting the return line but it din't help. Is it wrong if I put the formula just after the if else statement?
def cost_of_ground_shipping(weight):
#weight = float(weight)
if(weight<=2.0):
cost = (weight * 1.5) + 20.00
return cost
elif(weight>2.0) and (weight<=6.0):
cost = (weight * 3.00) + 20.00
return cost
elif(weight>6.0) and (weight>=10.0):
cost = (weight * 4.00) + 20.00
return cost
elif(weight>10.0):
cost = (weight * 4.75) + 20.00
return cost
print(cost_of_ground_shipping(8.4))
I expected the result 53.60
You have a typo: weight >= 10.0 should be weight <= 10.0. Since the function never reached a return statement, it implicitly returned None.
As well, we can improve the code by factoring out the calculation and return statement (see DRY), removing unnecessary parens, using Python's clearer range check syntax (x < y <= z), and using descriptive variable names:
def cost_of_ground_shipping(weight):
base = 20.0
if weight <= 2.0:
multiplier = 1.5
elif 2.0 < weight <= 6.0:
multiplier = 3.0
elif 6.0 < weight <= 10.0:
multiplier = 4.0
elif 10.0 < weight:
multiplier = 4.75
return weight * multiplier + base
print(cost_of_ground_shipping(8.4)) # -> 53.6
If you had written the code like this but still had the typo, the return line would have thrown an error: NameError: name 'multiplier' is not defined, which would be your first hint for starting debugging.

Python 3 - Temperature Converter

I am fairly new to any programing and I am trying to build a temperature converter function in python but I keep getting errors.
I wanted the function to first prompt the user for a temperature in Fahrenheit and convert it to Celsius;and next prompt the user for a temperature in Celsius and convert it to Fahrenheit. Below is my code. Any help will be appreciated
def main():
F = input("Input the temperature in Fahrenheit: ")
C = (5 / 9) * (float(F - 32))
print(int(C))
input("input the temperature in Celsius")
F = 9/5 * (float(C + 32))
Print(int(F))
main()
This is the error message I get:
Traceback (most recent call last):
File "/Users/mabook/Library/Preferences/PyCharmCE2018.2/scratches/scratch_7.py", line 11, in <module>
main()
File "/Users/mabook/Library/Preferences/PyCharmCE2018.2/scratches/scratch_7.py", line 4, in main
C = (5 / 9) * (float(F - 32))
TypeError: unsupported operand type(s) for -: 'str' and 'int'
The reason for your error as stated in the comments is that you can't take a string from an integer. So you need to convert you input to some type that you can take away from an integer like a float but you must do this before doing the calculation.
There are other things that need to be changed to make this code work:
print should be lower case
The second input needs to be stored in a variable so we can then use it
The brackets need to be changed when converting to Fahrenheit to make the formula correct
Unless you have some need to truncate the number back to an int and get rid of everything after the decimal point we may as well just print the result as is. If you do need the result as an int you should consider rounding to the nearest integer and not just truncating the value
With all these changes the code could look something like this:
def main():
F = input("Input the temperature in Fahrenheit: ")
C = (5 / 9) * (float(F) - 32)
print(C)
C = input("input the temperature in Celsius: ")
F = (9 / 5) * float(C) + 32
print(F)
main()

Python "int object is not callable"

TypeError: 'int' object is not callable
Anyone knows how can I fix this error? I know error is somewhere in the equation in the total. Thanks
decimal = 0
rate = 0
principal = 0
years = 0
def simple(p, r, n,):
decimal = r / 100
print("Principal: " + str(p))
print("Rate: " + str(decimal))
print("Number of Years: " + str(n))
total = p (1 + (decimal * n))
print("Total: " + str(total))
def main():
principal = int(input("Enter Principal: "))
rate = float(input("Enter Rate: "))
years = int(input("Enter Numbers of Years: "))
simple(principal, rate, years)
main()
print("End of Program")
Here p is an integer that you try to call :
total = p (1 + (decimal * n))
I think that you want :
total = p*(1 + (decimal * n))
On this line p is expected to be a function because it is immediately followed by a parenthesis:
total = p (1 + (decimal * n))
But p is passed as a parameter above, so I'm guessing you are passing an integer. If you mean to multiply:
total = p * (1 + (decimal * n))
You should define p first simple(int p,int r,int t) then total=p*(1+decim

Resources