I am new to Python and programming in general. I would like to know how to get rid of this compile error
def health_risk(activity_level, is_smoker):
"""Counts the aliveness of a person"""
alive = "alive?" or "sedentary"
very_low = "low" or "very low"
active = "active" or "very active"
if (activity_level in alive) and is_smoker is True:
xer = "extreme"
elif (activity_level in active) and is_smoker is True:
xer = "medium"
elif (activity_level == alive) and (is_smoker is False):
xer = "high"
elif (activity_level == very_low) and (is_smoker is False):
xer = "medium"
elif activity_level == active and is_smoker is False:
xer = "low"
return xer
level = health_risk('low', True)
print(level)
Thanks for the help and this is my first post, thanks.
Revise your variable statements to be assigned to lists.
alive = ["alive", "sedentary"]
very_low = ["low", "very low"]
active = ["active", "very active"]
Replace all == with in,
Include the missing elif statement.
elif (activity_level in very_low) and (is_smoker is True):
xer = "high" # or medium or whatever
note: to reduce redundancy, you could just put and is_smoker if it's True and and not is_smoker if it's False.
Related
I'm trying to write a short-ish script to entertain myself and potentially others. When I run it it tends to just skip over the if elif and else statements.
import random
adventure = ["fantasy" , "sci-fi" , "pirate" , "pre-history"]
setting = ["ocean", "forest" , "desert" , "castle"]
while True:
adven = []
setti = []
random.shuffle(adventure)
random.shuffle(setting)
adven.append(adventure[0])
setti.append(setting[0])
print(adven)
print(setti)
accept = input("Is this acceptable? ")
if accept == "y" :
print("Great, let us get started!")
break
else :
print("I am so sorry, lets try again!")
adve = []
sett = []
adve.append(adven)
sett.append(setti)
if adve == "fantasy" :
if sett == "ocean" :
print("1")
elif sett == "forest" :
print("2")
elif sett == "desert" :
print("3")
elif sett == "castle" :
print("4")
if adve == "sci-fi" :
if sett == "ocean" :
print("5")
elif sett == "forest" :
print("6")
elif sett == "desert" :
print("7")
elif sett == "castle" :
print("8")
if adve == "pirate" :
if sett == "ocean" :
print("9")
elif sett == "forest" :
print("10")
elif sett == "desert" :
print("11")
elif sett == "castle" :
print("12")
if adve == "pre-history" :
if sett == "ocean" :
print("13")
elif sett == "forest" :
print("14")
elif sett == "desert" :
print("15")
elif sett == "castle" :
print("16")
print(adve)
print(sett)
Would I need to keep it in the while True loop? I am not sure what to do because I want to make sure it works before I get any real details written into the script.
Try in. As in:
if "fantasy" in advve:
Will likely work better for you than == here.
Why? Because you're testing if a string is in a list of strings.
Don't forget to swap your operands around. Unlike == in cares which comes first.
As I understand, you would like to have multiple values in adven and setti, that's why it is a list?
So, firstly, you should take the definition of these values outside of loop scope:
adven = []
setti = []
while True:
...
You are appending list to list, so you getting list in list.
adve = []
adve.append(["random", "stuff"])
print(adve)
# [['random', 'stuff']]
Comparing a list to a string is always false because you compare different types of values.
print(adve == "random")
# False
print(["random"] == "random")
# False
To fix it you should:
# adve.append(adven)
adve = adven.copy() # or simply `adve = adven`, or just use adven instead adve.
print(adve)
# ['random', 'stuff']
And:
# adve == "random"
print("random" in adve)
# True
Btw, you should use pop() function so you wouldn't get duplicates:
# adven.append(adventure[0])
# setti.append(setting[0])
adven.append(adventure.pop())
setti.append(setting.pop())
If I misunderstood, and you don't need to handle multiple values for adven and setti, then your code should looks like this:
import random
adventure = ["fantasy", "sci-fi", "pirate", "pre-history"]
setting = ["ocean", "forest", "desert", "castle"]
while True:
random.shuffle(adventure)
random.shuffle(setting)
adven = adventure[0]
setti = setting[0]
print(adven)
print(setti)
accept = input("Is this acceptable? ")
if accept == "y":
print("Great, let us get started!")
break
else:
print("I am so sorry, lets try again!")
adve = adven
sett = setti
multiplier = 0
if adve == "fantasy":
multiplier = 1
elif adve == "sci-fi":
multiplier = 2
elif adve == "pirate":
multiplier = 3
elif adve == "pre-history":
multiplier = 4
else:
print(f"issue with adve: {adve}")
if sett == "ocean":
print(multiplier * 1)
elif sett == "forest":
print(multiplier * 2)
elif sett == "desert":
print(multiplier * 3)
elif sett == "castle":
print(multiplier * 4)
print(adve)
print(sett)
I'm making a leveling system and it only levels me up once and then stops working. Once it levels me the xp doesn't reset and my level does not go up. Here's the code!
level = int(1)
crexp = int(260)
reqxp = int(100)
while crexp >= reqxp:
level = level+1
crexp = crexp-reqxp
reqxp = (reqxp/100)*120
continue
while 3 > 2:
pinput = input()
if pinput == "1":
crexp = crexp + 60
elif pinput == "2":
print(level)
elif pinput == "3":
print(crexp)
elif pinput == "4":
print(reqxp)
elif pinput == "5":
break
The problem with your current code is that you are not rerunning the 'level up' part of the code. Python generally (when not in a while/for loop e.c.t) reads your code from top to bottom. This means by the time you get into the second while loop the first while loop has finished and will never be run again.
To fix this you want to tell python to recalculate the level and experience variables at certain points - the easiest way to do this is to make the first while loop into a function and call it at the start of the second while loop. You would get something like this -
def checkLevelUp(currentXp, requiredXp, currentLevel):
while currentXp >= requiredXp:
currentLevel = currentLevel+1
currentXp = currentXp-requiredXp
requiredXp = int(requiredXp * 1.2)
return currentLevel, currentXp, requiredXp
level = 1
crexp = 260
reqxp = 100
while True:
level, crexp, reqxp = checkLevelUp(crexp, reqxp, level)
pinput = input()
if pinput == "1":
crexp = crexp + 60
elif pinput == "2":
print(level)
elif pinput == "3":
print(crexp)
elif pinput == "4":
print(reqxp)
elif pinput == "5":
break
Note also the changes to calculating the next required xp - dividing by 100 and then multiplying by 120 is just the same as multiplying by 1.2.
Its suppose to print:
no food
breakfast,marmalade
breakfast,coffee
lunch,dessert
dinner
no food
no food
dinner,dessert
def food(input,boolean):
time = int(input)
food_type = ""
if time >= 0 and time < 6 or time >= 22:
food_type = "no food"
if time >= 6 and time <= 10:
food_type = "breakfast"
if time >= 11 and time <= 15:
food_type = "lunch"
if time >= 16 and time < 22:
food_type = "dinner"
dessert = ""
if boolean == True and food_type == "breakfast":
dessert = "marmalade"
if boolean == False and food_type == "breakfast":
dessert = "coffee"
if boolean == True and food_type == "lunch":
dessert = "dessert"
if boolean == True and food_type == "dinner":
dessert = "dessert"
return ','.join((food_type, dessert))
Basically right now, I have a comma between return '' so it will print breakfast, marmalade but then when it comes to no food it adds a comma in the end, so it looks like no food,
Its suppose to look like:
no food
breakfast,marmalade
breakfast,coffee
lunch,dessert
dinner
no food
no food
dinner,dessert
I'm not 100% certain the about the output you want, but I think you want to not have the dessert or the comma if the food_type would be "no food", even if the boolean is True. I can think of at least two different ways to do that.
The first way is to replace
food_type = "no food"
with
return "no food"
Another way would be to replace
return ','.join((food_type, dessert))
with
output = food_type
if output != "no food":
output = ','.join((food_type, dessert))
return output
Some people would prefer the second one since there is only one return.
I'm not sure what seems to be the problem with my code, I need some help. When I try running my program, it says invalid syntax next to my first if, I thought I may be an indentation error but nothing is working.
Here is my code:
import random
def montyHall():
car = random.randint(1,3)
guess1 = random.randint(1,3)
for i in range(1,3):
if ((not(i == car) and not(i == guess1)):
return i
newGuess = not(i) and not(guess1)
if (newGuess == car):
stay = True
elif (guess1 == car):
switch = False
return strategyOne
NUM_OF_TRIALS = 1000
stay = 0
switch = 0
for i in range(NUM_OF_TRIALS):
if(montyHall()):
stay += 1
else:
switch += 1
print("Staying wins", stay/NUM_OF_TRIALS, "% of the time")
print("Switching wins", switch/NUM_OF_TRIALS, "% of the time")
To many brackets and you do not need brackets in python.
Try changing:
if ((not(i == car) and not(i == guess1)):
to
if i != car and i != guess1:
I keep having this error on my bot program:
start.py:890 local variable 'cmd_part_1' referenced before assignment
Code:
try:
my_alias = message.body.split(" ", 3)
if len(my_alias) > 2:
cmd_part_1 = my_alias[0]
cmd_part_2 = my_alias[1]
elif len(my_alias) < 2:
cmd_part_1 = ""
cmd_part_2 = ""
except Exception as e:
cmd_part_1 = ""
cmd_part_2 = ""
if self.getAccess(user.name.lower()) >= lvl_config.rank_req_callme and cmd_part_1 == "call" and cmd_part_2 == "me":
whole_body = message.body
whole_body = whole_body.replace("call me ", "");
whole_body = whole_body.replace(",", ",");
chat_message("<font color='#%s' face='%s' size='%s'>%s <b>%s</b></font>" % (font_color, font_face, font_size, random.choice(["Recorded! ^_^ I will now call you", "Registah'd, you are now", "Yo, dis mah big homie, I call dem", "Ye-a-a-ah, I guess I can call you that...", "If I have to.. I suppose I'll call you..", "I decided I will call you"]), whole_body), True)
alias_flag = 0
finished_proc = 1
file = open("storage/flatfile/various/aliases.csv", "r")
for line in file.readlines():
alias_data = line.strip()
alias_username, alias_nickname = alias_data.split(",", 1)
Error Line:
if self.getAccess(user.name.lower()) >= lvl_config.rank_req_callme and cmd_part_1 == "call" and cmd_part_2 == "me":
What am I doing wrong?
You have if and elif statements in the first try block that set cmd_part_1.
What happens if none of the conditions in these if statements is True?
In that case, cmd_part_1 will never be assigned a value. This is what is going on in your code. Fix this and it will work. Maybe add an else clause there and assign a default value to both cmd_part_1 and cmd_part_2. Or make one of them have an =.
For example:
if len(my_alias) >= 2:
instead of:
if len(my_alias) > 2:
After that, as eryksun suggested in the comment below, you can replace the elif with an else.