Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 months ago.
Improve this question
I want to write the following program by using User-Defined Functions.
The following program is used to calculate Total Daily Energy Expenditure(TDEE).
When input Basal Metabolic Rate(BMR) and activity level ,it will output Total Daily Energy Expenditure.
Here is my code.
def TDEE1(BMR):
return BMR*1.2
def TDEE2(BMR):
return BMR*1.375
def TDEE3(BMR):
return BMR*1.55
BMR=float(input("BMR:"))
activitylevel=float(input("activitylevel:"))
tdee1=TDEE1(BMR)
tdee2=TDEE2(BMR)
tdee3=TDEE3(BMR)
if activitylevel==0:
print("TDEE:",tdee1)
elif activitylevel==1:
print("TDEE:",tdee2)
elif activitylevel==2:
print("TDEE:",tdee3)
I think it is a little complex.
How can I make it more concise?
You could do this:
bmr = float(input("BMR:"))
activitylevel = int(input("activitylevel:"))
print("TDEE:", (1025 + activitylevel * 175) * bmr / 1000)
Note that this allows activitylevel to be other integers than 1, 2 or 3, but then the output will use a linear extrapolation of the given coefficients.
You can use this:
bmr = float(input('BMR: ')) # Get BMR
level = input('Activity level: ') # Get activity level and keep it as a string
switch = {'0': 1.2, '1': 1.375, '2': 1.55} # Multiplications
print(bmr * switch.get(level, 1.2)) # Multiply by correct number, defaults to level 0 if invalid response entered
Output:
BMR: 7000
Activity level: 1
9625.0
How about:
def get_tdee(BMR, activity_level):
return BMR*(0.175*activity_level + 1.025)
bmr_in=float(input("BMR:"))
activity_level_in=float(input("activitylevel:"))
print("TDEE:", get_tdee(bmr_in, activity_level_in))
The main reason is that you needn't set up three functions to handle different activitylevels, because you will do the same operation to all activitylevels, so just one function (even can be omitted because the operation is easy, just a multiplication.) is needed.
BMR=float(input("BMR:")) # get input
TDEE=[1.2, 1.375, 1.55] # update the list on demand, it needn't be hardcoded
activitylevel=input("activitylevel:") # input index of TDEE
print(BMR*TDEE[activitylevel]) # return BMR * list[index]
Something like this:
TDEE=[1.2, 1.375, 1.55]
BMR=float(input("BMR:"))
activitylevel=int(input("activitylevel:"))
if activitylevel >=0 and activitylevel <=2:
print("TDEE:", TDEE[activitylevel] * BMR)
else:
print("Invalid activity level")
Do not calculate anything you are not going to use.
base = [ 1.2,1.375,1.55 ]
BMR=float(input("BMR:"))
activitylevel=int(input("activitylevel:"))
print(BMR*base[activitylevel])
maybe you can try this.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Below is my first python program. I am trying idea not yet covered in class as i hate staying stagnant and want to solve issues that may arise if i were to just use the info we've learned in class. As for my question, the program works but what were be ways to condense the code, if any? Thanks!
#This is a program to provide an itemized receipt for a campsite
# CONSTANTS
ELECTRICITY=10.00 #one time electricity charge
class colors:
ERROR = "\033[91m"
END = "\033[0m"
#input validation
while True:
while True:
try:
nightly_rate=float(input("Enter the Basic Nightly Rate:$"))
except ValueError:
print(colors.ERROR +"ERROR: Please Enter the Dollar Amount"+colors.END)
else:
break
while True:
try:
number_of_nights=int(input("Enter the Number of Nights You Will Be Staying:"))
except ValueError:
print(colors.ERROR +"ERROR: Please Enter a Number"+colors.END)
else:
break
while True:
try:
campers=int(input("Enter the Number of Campers:"))
except ValueError:
print(colors.ERROR +"ERROR: Please Enter a Number"+colors.END)
else:
break
break
#processing
while True:
try:
campsite=nightly_rate*number_of_nights
tax=(ELECTRICITY*0.07)+(campsite*0.07)
ranger=(campsite+ELECTRICITY+tax)*0.15 #gratuity paid towards Ranger
total=campsite+ELECTRICITY+tax+ranger #total paid per camper
total_per=total/campers
except ZeroDivisionError: #attempt to work around ZeroDivisionError
total_per=0 #total per set to zero as the user inputed 0 for number-
break #-of campers
#Output #Cant figure out how to get only the output colored
print("Nightly Rate-----------------------",nightly_rate)
print("Number of Nights-------------------",number_of_nights)
print("Number of Campers------------------",campers)
print()
print("Campsite--------------------------- $%4.2f"%campsite)
print("Electricity------------------------ $%4.2f"%ELECTRICITY)
print("Tax-------------------------------- $%4.2f"%tax)
print("Ranger----------------------------- $%4.2f"%ranger)
print("Total------------------------------ $%4.2f"%total)
print()
print("Cost Per Camper------------------- $%4.2f"%total_per)
The else in try statement is unnecessary. You can just put the break in the the end of the try statement. REF
In the end, in the print statements, I recommend you to use another types of formatting. You can use '...{}..'.format(..) or further pythonic is f'...{val}'. Your method is the oldest. More ref
You can remove both the outer while loops, as break is seen there at the top level, so the loops runs once only.
You can convert colors to an Enum class if desired (this is more of a stylistic choice tbh)
The line tax=(ELECTRICITY*0.07)+(campsite*0.07) can be represented as x*0.07 + y*0.07, which can be simplified to 0.07(x+y) or 0.07 * (ELECTRICITY + campsite) in this case.
Instead of manually padding the - characters in the print statements, you can use f-strings with simple formatting trick.
For example, try this out:
width = 40
fill = '-'
tax = 1.2345
print(f'{"Tax":{fill}<{width}} ${tax:4.2f}')
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Using python I'm creating a code that receives a list of lists as parameter. This list of lists contains names and grades of students. The function also must print the name of the student with the best grade and its best grade. When I created the code and try to run it nothing occurs is there a way to improve my code? My desired output would be "The best student is: Caroline with a 9.6"
students=[["steve", 9.0], ["ben", 9.5], ["Caroline",9.6],["Tim", 9.1]]
highest_grade=[]
lowest_grade=[]
def best():
i = 1
max = min = students[0]
# first, calculate the max and min.
while i < len(students): # (possible improvement: replace this with a for loop)
if students[i] > max:
max = students[i] # replace max with the new max
if students[i] < min:
min = students[i] # replace min with the new min
i += 1
highest_grade.append(max)
lowest_grade.append(min)
print("The best student is:",best())
There are a few things you could do to improve it. You find the min score but don't use it, so I'm not sure if you need it. If you do need it, you could add it to your return statement. Here's a suggested way to do it that should be easy to follow:
students = [["steve", 9.0], ["ben", 9.5], ["Caroline", 9.6], ["Tim", 9.1]]
def best(students):
highest_grade_name = None
lowest_grade_name = None
my_max_score = -float("inf")
my_min_score = float("inf")
for name, score in students:
if score > my_max_score:
my_max_score = score
highest_grade_name = name
if score < my_min_score:
my_min_score = score
lowest_grade_name = name
return my_max_score, highest_grade_name
best_name, best_score = best(students)
print(f"The best student is {best_name} with a score of {best_score}")
max(students,key=lambda x:x[1])
I think would work
There could be quite a few improvements to this piece of code. Firstly, it would be far better if the students array was a dict, but it's understandable if it absolutely has to be an array of arrays.
Secondly, you're right, you should do this with a for loop:
def best_student_grade():
highest_grade = 0 # "max" is a terrible name for a variable
for student, grade in student:
if grade > highest_grade:
grade = highest_grade
best_student = student
return highest_grade, best_student
bstudent, bgrade = best_student_grade()
print(f"The best student is: {bstudent} with a {bgrade}")
You could even do this with a list comprehension, but I will leave that as an exercise to the reader.
In all honesty, I think it would benefit you in a lot of ways to read some introductory python or programming books.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to create a simple AI program which plays stick game. The problem is that I would like to subtract chosen stick from the total stick number. This simple code shows some error such as nonexisting value. I could not assign returning value for my values. Is there another way to subtracts value with functions?
import random
msg = input('Determine stick numbers:')
print('Stick number is determined as:', msg)
# First player move
def robot(stick):
y = stick % 4
if y==0:
y=randint(1,3)
mov=int(y)
print('machine chose:', mov)
total = stick-mov
return total
def human(stick2):
mov2= int(input('your turn:'))
print('human chose:', mov2)
total = stick2-mov2
return total
players= {
'1': robot,
'2': human
}
number1= input('Determine first player machine(1) or human(2):')
number2= input('Determine second player (1) or (2):')
player1=players[number1]
player2=players[number2]
print(player1, player2)
print('the game begins')
while True:
player1(int(msg))
if msg == 0: break
print('remained sticks:', msg)
player2(int(msg))
print('remained sticks:', msg)
if msg == 0: break
Your players are references functions:
players= {
'1': robot,
'2': human
}
Later you call them player1 and player2:
player1=players[number1]
player2=players[number2]
But when you use these functions you don't do anything with the return value:
player1(int(msg))
...
player2(int(msg))
So those functions return something, but you ignore the value. You need to either print that return value or assign it to a variable so you can do something with the value later.
Since your return values are called total perhaps you want:
total = player1(int(msg))
print('new total:', total)
return does work, of course; it returns a value. However in your code you are not capturing that value and it is immediately thrown away.
It's really not clear what you want, but perhaps you want something like this:
msg = player1(int(msg))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
In my code:
def get_drink_price (drink):
int 0.75 == "Coke"
if get_drink_price("Coke"):
return Coke
# This is just to see what prints
print get_drink_price("Coke")
I keep getting this error message:
File "<stdin>", line 2
int 0.75 == "Coke"
^
SyntaxError: invalid syntax
What's that?
...because that isn't valid Python syntax. You have the following problems:
You should use int(n) to turn n into an integer. int on its own isn't valid (hence the SyntaxError) - you could define a variable called int, (e.g. int = 1) but that uses a single equals sign and should never be done, as you shadow the built-in int();
0.75 == "Coke" is a boolean comparison, not any kind of assignment (and will never be True);
You keep recursively calling get_drink_price with no way to return; and
Coke is never defined, so return Coke would cause a NameError anyway.
It is completely unclear what you are trying to achieve with that function, but maybe:
def get_drink_price(drink):
drinks = {'Coke': 0.75, 'Orange': 0.6} # dictionary maps drink to price
return drinks[drink] # return appropriate price
Now
>>> get_drink_price("Coke")
0.75
Perhaps closer to what you were trying to do:
def get_drink_price(drink):
Coke = 0.75 # define price for Coke
if drink == "Coke": # test whether input was 'Coke'
return Coke # return Coke price
but you should be able to see that the dictionary-based implementation is better.
I have a feeling that the code you are looking to create should be done something more like this:
def get_drink_price(drink):
prices = { "Coke":0.75, "Pepsi":0.85}
return prices[drink]
print get_drink_price("Coke")
The prices object in the function is just a dictionary, which is a standard python object. You can look up more information about dictionaries here: http://docs.python.org/2/tutorial/datastructures.html#dictionaries, but if what you're looking to do is find the price of a drink from its name, this is a simple, straightforward approach.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is it possible to combine these functions together to create 1 function?
def checkinput():
while True:
try:
name=input("whats your name?")
return name
except ValueError:
print("error!")
Combined with:
def checkage():
while True:
try:
age=input("whats your age?")
return age
except ValueError:
print("error!")
Thanks in advance!
You can refactor the code to create one function that handles both cases, by recognizing the parts that are the same, and parameterizing the other parts.
def check_value(prompt):
while True:
try:
val=input(prompt)
return val
except ValueError:
print("error!")
The only difference between the two functions (other than trivial differences like variable names) was the prompt shown by the input function. We make that a parameter to the new unified function, and call it like this:
x = check_input("What's your name?")
y = check_input("What's your age?")
Why you expect input to possibly raise a ValueError is a different question.
If you want to generalize your code, you could write one function that can ask any number of questions.
You can create a function that looks like this:
def ask_a_question(prompt):
while True:
try:
answer = input(prompt)
except ValueError:
print("Error!")
else:
return answer
For example, in your main() function, you could have a list of prompts:
prompts = {
'name': 'What is your name?',
'age': 'How old are you?',
'dog': 'Do you love dogs more than cats? (yes, you do)',
}
And finally you would create a loop that would ask all your questions one by one:
answers = {} # a dictionary of answers
for key, prompt in prompts.items():
answers[key] = ask_a_question(prompt)
Hopefully that gives you some ideas on how to reduce duplication of similar functions.
You can easily call a function from other functions:
def check_user_data():
checkinput()
checkage()
But really, this is a silly thing to do. If you just want their name and age you'd be better off doing something like this:
def get_user_info():
name = input("What is your name? ")
age = input("What is your age? ")
return name, age
You're never going to get a ValueError when you're just taking input - if you were doing int(input('What is your age? ')) you could get a ValueError, but otherwise the rest of your code is superfluous.
Yes!
def check_input_and_age():
return checkinput(), checkage()