Python, have an error message i keep receiving [closed] - python

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.

Related

How to write this program in a easier way? [closed]

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.

Tips For an Intro Python Program [closed]

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}')

Having multiple correct answers in a user defined dictionary [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm writing a review quiz for a pharmacology class. I switched styles based on feedback I received to a different question but have encountered a problem. I want to have multiple correct answers as the user may enter the answer slightly differently.
The previous format I was using would have looked something like this:
x = "What is the starting dose for oral Enalipril in HTN?"
ques1 = enterbox(msg = x, title = version)
if ques1.lower() in ["2.5-5", "2.5-5mg","2.5mg"]:
add()
#which is a function I had described above to track points and display that the answer was correct
ques2()
elif ques1.lower() in ["skip"]:
skip()
que2()
else:
loss()
que1()
"Skip" and "Loss" are just basic functions to keep track of skipped and wrong inputs.
Now the new format I'm trying to use is:
from easygui import enterbox
question_answer_pairs = [
("What Class of medication is Enalapril?", "ACE Inhibitor"),
("What is the starting oral dose of Enalapril for HTN?", ["2.5-5mg", "2.5-5","2.5mg"]),
("which type of metabolism provides the maximum amount of ATP needed for contraction?", "aerobic")
]
VERSION = 'Pharmacology Prep Exam'
class ResultStore:
def __init__(self):
self.num_correct = 0
self.num_skipped = 0
self.num_wrong = 0
def show_results(self):
print("Results:")
print(" Correct:", self.num_correct)
print(" Skipped:", self.num_skipped)
print(" Wrong: ", self.num_wrong)
def ask_question(q, a, rs, retry_on_fail=True):
while True:
resp = enterbox(msg=q, title=VERSION)
# Force resp to be a string if nothing is entered (so .lower() doesn't throw)
if resp is None: resp = ''
if resp.lower() == a.lower():
rs.num_correct += 1
return True
if resp.lower() == "skip":
rs.num_skipped += 1
return None
# If we get here, we haven't returned (so the answer was neither correct nor
# "skip"). Increment num_wrong and check whether we should repeat.
rs.num_wrong += 1
if retry_on_fail is False:
return False
# Create a ResultsStore object to keep track of how we did
store = ResultStore()
# Ask questions
for (q,a) in question_answer_pairs:
ask_question(q, a, store)
# Display results (calling the .show_results() method on the ResultsStore object)
store.show_results()
(The above code is almost taken verbatim from a different user that responded to a different question, it works but I take no credit for writing it)
OK, hopefully that copied and pasted correctly, but it functions fine for the first question but crashes on the second one, returning:
File "./APPrac.py", line 7, in <module>
("which type of metabolism provides the maximum amount of ATP needed for contraction?", "aerobic")
TypeError: 'tuple' object is not callable
I tried getting rid of the brackets and throwing in "or" between the answers but got the same error.
I'm pretty much shooting in the dark at this point because I'm not even entirely sure how to search for help.
I'm completely self taught so all the Barney level explanations provided mean the world to me.
Thanks
EDIT: So placing the comma in line 6 corrected the problem. But I get the following error now
Traceback (most recent call last):
File "./dict.py", line 47, in <module>
ask_question(q, a, store)
File "./dict.py", line 29, in ask_question
if resp.lower() == a.lower():
AttributeError: 'list' object has no attribute 'lower'
It goes away if I remove the question with multiple answers though.
You're missing a comma, so instead of having a list like [(...), (a, b), (c, d)] you actually have a list that looks like [(...), (a, b)(c, d)] where it thinks your calling the second object (a, b) with the arguments (c, d).
Change
question_answer_pairs = [
("What Class of medication is Enalapril?", "ACE Inhibitor"),
("What is the starting oral dose of Enalapril for HTN?", ["2.5-5mg", "2.5-5","2.5mg"])
("which type of metabolism provides the maximum amount of ATP needed for contraction?", "aerobic")
]
to
question_answer_pairs = [
("What Class of medication is Enalapril?", "ACE Inhibitor"),
("What is the starting oral dose of Enalapril for HTN?", ["2.5-5mg", "2.5-5","2.5mg"]), # <-- this comma was missing
("which type of metabolism provides the maximum amount of ATP needed for contraction?", "aerobic")
]

How can I return with a local variable in definition in Python? [closed]

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))

python - Is it possible to combine 2 functions together to create 1 function? [closed]

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()

Categories

Resources