If/ Elses statement not executing properly - python-3.x

I've altered the if/else statements several times and either only the if statement will be executed even if it's not true or only the else statement will be executed even if it's not true.
def interview():
""" NoneType -> NoneType
Interview the user. """
name = input("What is your name?")
unit = input("What is you preferred choice of unit - standard or imperial?")
weight = float(input("What is your weight?"))
height = float(input("What is your height?"))
a = float(bmi_std(weight, height))
b = float(bmi_std_prime(weight, height))
c = float(bmi_imp(weight, height))
d = float(bmi_imp_prime(weight, height))
e = str(category(weight, height, 's'))
f = str(category(weight, height, 'i'))
print("So," + name + ", your preferred unit is" + unit + ".")
print("Your weight", weight)
print("Your height", height)
if str(unit == 'imperial'):
print("BMI = " + str(c) + " and your BMI prime = " + str(d))
print("Category = " + f)
else:
print("BMI = " + str(a) + " and your BMI prime = " + str(b))
print("Category = " + e)
This is just part of my code. Is there something wrong in the way its written because it looks fine to me. I'm only an intro to programming.

I can see an issue right away
if str(unit == 'imperial'): should be if str(unit) == 'imperial':

Related

Improving in function clarity and efficiency in python

I am very new in programming so I need help in "cleaning up my code" if the code is a mess if not then please recommend some better commands that accomplish the same purpose of any line or multiple lines.
Here is my program.
import random
def random_num():
lower_bound = input("what is your lower bound: ")
upper_bound = input("What is your upper bound: ")
trials = input("How many time would you like to try: ")
random_number = random.randint(int(lower_bound),
int(upper_bound))
user_input = input(
"What is the number that I am thinking in the range "
+ lower_bound + "-" + upper_bound + " (only " + trials + " tries): ")
ending = "Thanks For Playing"
continue_game = "That's it. Do you want to continue the game?
(Yes/No): "
count = 0
while True:
answer = int(user_input)
if count == int(trials) - 1:
lost = input("Sorry you have lost " + continue_game).lower()
if lost in ["yes"]:
random_num()
else:
return ending
else:
if answer == random_number:
win = input(continue_game).lower()
if win in ["yes"]:
random_num()
else:
return ending
elif answer >= random_number:
user_input = input("The number is smaller than that: ")
else:
user_input = input("The number is bigger than that: ")
count += 1
print(random_num())

AttributeError: 'list' object has no attribute 'feature'

def tree_to_code(tree, feature_names):
tree_ = tree.estimators_
#print(tree_)
feature_name = [
feature_names[i] if i != _tree.TREE_UNDEFINED else "undefined!"
for i in tree_.feature
]
print("def tree({}):".format(", ".join(feature_names)))
symptoms_present = []
def recurse(node, depth):
indent = " " * depth
if tree_.feature[node] != _tree.TREE_UNDEFINED:
name = feature_name[node]
threshold = tree_.threshold[node]
print(name + " ?")
ans = input()
ans = ans.lower()
if ans == 'yes':
val = 1
else:
val = 0
if val <= threshold:
recurse(tree_.children_left[node], depth + 1)
else:
symptoms_present.append(name)
recurse(tree_.children_right[node], depth + 1)
else:
present_disease = print_disease(tree_.value[node])
print( "You may have " + present_disease )
red_cols = reduced_data.columns
symptoms_given = red_cols[reduced_data.loc[present_disease].values[0].nonzero()]
print("symptoms present " + str(list(symptoms_present)))
print("symptoms given " + str(list(symptoms_given)) )
confidence_level = (1.0*len(symptoms_present))/len(symptoms_given)
print("confidence level is " + str(confidence_level))
recurse(0, 1)
tree_to_code(clf,cols)
While changing decision tree code to random forest code,we got an attribute error at line 6 : for i in tree_.feature. Please help us to solve the error. It works using decision tree classifier but not using Random Forest Classifier .
List item

It keep giving me the syntax error message when I can't find why it won't allow it

I was doing the assignment when this came up and as I am just a beginner I have no idea what is going on or how to solve it.
All the commented parts are just me trying out different ways to do it.
import sys
# YOUR CODE HERE
#small = input("Width, Height and Depth of small box: ")
#big = input("Width, Height and Depth of big box: ")
small_width = input("What is the width of the small box? ")
small_height = input("What is the height of the small box? ")
small_depth = input("What is the depth of the small box? ")
#small = 0
small = int(small_width)*int(small_height)*int(small_depth)
big_width = input("What is the width of the big box? ")
big_height = input("What is the height of the big box? ")
big_depth = input("What is the depth of the big box? ")
#big = 0
big = int(big_width)*int(big_height)*int(big_depth)
num = big%small
num = int(num)
print(num)
#if int(num) > 0
#print("Number of " + small + " that will fit in " + big + " is: " + num)
#else:
#print("Number of " + small + " that will fit in " + big + " is: 0")
It keeps saying this part is wrong.
#if int(num) > 0
^
You are missing a colon after the if statement.
Download and install PyCharm (there is a free edition) - the IDE will highlight such errors.
import sys
# YOUR CODE HERE
#small = input("Width, Height and Depth of small box: ")
#big = input("Width, Height and Depth of big box: ")
small_width = input("What is the width of the small box? ")
small_height = input("What is the height of the small box? ")
small_depth = input("What is the depth of the small box? ")
#small = 0
small = int(small_width)*int(small_height)*int(small_depth)
big_width = input("What is the width of the big box? ")
big_height = input("What is the height of the big box? ")
big_depth = input("What is the depth of the big box? ")
#big = 0
big = int(big_width)*int(big_height)*int(big_depth)
num = big%small
num = int(num)
print(num)
if int(num) > 0:
print("Number of {} that will fit in {} is: {}".format(small, big, num))
# print("Number of " + small + " that will fit in " + big + " is: " + num)
else:
# print("Number of " + small + " that will fit in " + big + " is: 0")
print("Number of {} that will fit in {} is: {}".format(small, big, 0))
You are missing a colon(:) at the end of the if statement. If you add it you will see that your problem on that line is fixed, but you will have another problem in the print statement of the if condition because you will be printing a text result trying to concatenate int variables.

Correcting logic on a return option on a loop python 3.6

I was taking a online class for Python and one of the tutorials is to create a battle system for a RPG. I finished the tutorial and felt that there was so much missing. One of the missing features was there is no option to go back to a players action which can lead to an infinite loop. I have coded a large section to include a way to go back by typing '0' and it works except for when there is no quantity for an item when selecting items and when there is no more MP for a spell. What happens in that case is when '0' is selected, the last entry on the array is automatically implemented. So lets say I have no MP and 'cura' is my last spell on the list, if I select '0' cura gets cased regardless. Can anyone tak a look at this small section I have included to see where the error is? I will include the entire code if needed.
while running:
print("====================\n")
print("NAME HP MP")
for player in players:
player.get_stats()
print("")
for enemy in enemies:
enemy.get_enemy_stats()
for player in players:
# check if player won
if defeated_enemies == 3:
print("\n" + bcolors.OKGREEN + "You Win!\n♫♫ Fanfare ♫♫" + bcolors.ENDC)
running = False
break
start = True
while start:
start = False
choice = player.choose_action()
index = choice - 1
if index == 0:
dmg = player.generate_damage()
enemy = player.choose_target(enemies)
enemies[enemy].take_damage(dmg)
print("\n" + player.name.replace(" ", "") + " attacked " + enemies[enemy].name.replace(" ", "") + " for", dmg, "points of damage.")
if enemies[enemy].get_hp() == 0:
print(bcolors.BOLD + bcolors.FAIL + enemies[enemy].name.replace(" ", "") + " HAS FALLEN!" + bcolors.ENDC)
del enemies[enemy]
defeated_enemies += 1
elif index == 1:
check_mp = True
while check_mp:
mag_choice = player.choose_magic()
magic_choice = mag_choice - 1
spell = player.magic[magic_choice]
magic_dmg = spell.generate_damage()
current_mp = player.get_mp()
if spell.cost > current_mp:
print(bcolors.FAIL + "\nNot enough MP. Please choose a different spell. Type 0 to go back." + bcolors.ENDC)
continue
else:
check_mp = False
if magic_choice == -1:
start = True
continue
player.reduce_mp(spell.cost)
if spell.type == "white":
player.heal(magic_dmg)
print(bcolors.OKBLUE + "\n" + spell.name + " heals", player.name, "for", str(magic_dmg), "HP." + bcolors.ENDC)
if player.hp > player.maxhp:
player.hp = player.maxhp
elif spell.type == "black":
enemy = player.choose_target(enemies)
enemies[enemy].take_damage(magic_dmg)
print(bcolors.OKBLUE + "\n" + spell.name + " deals", str(magic_dmg), "points of damage to " + enemies[enemy].name.replace(" ", "") + bcolors.ENDC)
if enemies[enemy].get_hp() == 0:
print(bcolors.BOLD + bcolors.FAIL + enemies[enemy].name.replace(" ", "") + " HAS FALLEN!" + bcolors.ENDC)
del enemies[enemy]
defeated_enemies += 1
elif index == 2:
choose_item = True
while choose_item:
itm_choice = player.choose_item()
item_choice = itm_choice -1
item = player.items[item_choice]["item"]
if player.items[item_choice]["quantity"] == 0:
print(bcolors.FAIL + "\nThere are no more " + str(item.name) +"s left. Please choose a different item. Type 0 to go back." + bcolors.ENDC)
continue
else:
break
if item_choice == -1:
start = True
continue
player.items[item_choice]["quantity"] -= 1
if item.type == "potion":
player.heal(item.prop)
print(bcolors.OKGREEN + "\n" + item.name + " heals", player.name, "for", str(item.prop), "HP." + bcolors.ENDC)
if player.hp > player.maxhp:
player.hp = player.maxhp
elif item.type == "elixer":
if item.name == "MegaElixer":
print("\n" + player.name.replace(" ", ""), "uses", item.name)
print(bcolors.OKGREEN + "HP and MP fully restored to all party members!" + bcolors.ENDC)
for i in players:
i.hp = i.maxhp
i.mp = i.maxmp
else:
player.hp = player.maxhp
player.mp = player.maxmp
print(player.name.replace(" ", ""), "uses", item.name)
print(bcolors.OKGREEN + player.name.replace(" ", "") + " HP and MP fully restored!" + bcolors.ENDC)
elif item.type == "attack":
enemy = player.choose_target(enemies)
enemies[enemy].take_damage(item.prop)
print(bcolors.FAIL + "\n" + item.name + " deals", str(item.prop), "points of damage to " + enemies[enemy].name.replace(" ", "") + bcolors.ENDC)
if enemies[enemy].get_hp() == 0:
print(bcolors.BOLD + bcolors.FAIL + enemies[enemy].name.replace(" ", "") + " HAS FALLEN!" + bcolors.ENDC)
del enemies[enemy]
defeated_enemies += 1
else:
continue

Python: Using Variable From Different Function Without Renaming

I'm working on creating a short battle from a game (for fun). I have several variables that need to change throughout the sequence, such as m_hp (monster health). Here is the code I have (Forgive me if I formatted incorrectly, this is my first time using this website):
def battle(p_lvl):
print("A goblin engages you in battle!")
p_hp = p_lvl * 25 + 25
p_dmg = p_lvl * 7 + 5
print("Player Stats (Level: " + str(p_lvl) + " Health: " + str(p_hp) + " ATK: " + str(p_dmg) + ")")
m_lvl = p_lvl - 1
m_hp = m_lvl * 20 + 15
m_dmg = m_lvl * 6 + 3
scr_dmg = m_hp / 4
dus_eft = p_hp / 5
print("Goblin Stats (Level: " + str(m_lvl) + " Health: " + str(m_hp) + " ATK: " + str(m_dmg) + ")")
act()
def act():
menu = 'Attack','Block','Use Item'
print("What will you do?")
print(menu)
action = input()
if action == ‘Attack':
m_hp = m_hp - p_dmg
print("You dealt " + str(p_dmg) + "damage to the goblin!")
p_hp = p_hp - m_dmg
print("The goblin struck back with " + str(m_dmg) + " damage!”)
act()
I get problems after act() initiates. If I enter "attack" for the input(), I get this error:
UnboundLocalError: local variable 'm_hp' referenced before assignment
To my understanding, this is because I have m_hp placed under battle(), but act() cannot reach it. I want to be able to change m_hp without writing it in act(). I believe if I do so, then m_hp will reset each time act() initiates, and m_hp cannot drop. I've searched through questions on here, but the cases I've seen don't seem to work. Also, I am admittedly new to coding, so I couldn't understand some of the solutions.
Tl;dr I'm looking for a simple solution as to how to use variables from a different function without putting them into the function.
You're seeing that error message because the 'm_hp' variable is local to the scope of the 'battle' function. It is created inside the function, and ceases to exist after that function exits.
It doesn't look like battle actually gets called anywhere though...
It also looks like you call the act() function before you define it.
There are a number of other reasons why the code would not run if that error was fixed as well.
The feature you're probably looking for where you have access to variables inside multiple functions without passing them in is some kind of global variable. In general, global variables are strongly discouraged anywhere they can be reasonably avoided.
I've retooled your code a bit so that you have something working to mess around with. I've used classes to try to group related things together.
There is now a 'Player' object with all the player's stats and a 'Monster' object with all the monster's stats.
Try running the code below, then making incremental changes and seeing if it continues to run.
class Player(object):
def __init__(self, level):
self.level = level
self.stats_for_level()
def stats_for_level(self):
self.attack_damage = (self.level * 7) + 5
self.hitpoints = (self.level * 25) + 25
def take_damage(self, damage):
self.hitpoints -= damage
def print_stats(self):
print("Player Stats (Level: " + str(self.level) +
" Health: " + str(self.hitpoints) +
" ATK: " + str(self.hitpoints) + ")")
class Monster(object):
def __init__(self, level, name="Goblin"):
self.level = level
self.name = name
self.stats_for_level()
def stats_for_level(self):
self.attack_damage = (self.level * 6) + 3
self.hitpoints = (self.level * 20) + 15
def take_damage(self, damage):
self.hitpoints -= damage
def print_stats(self):
print(self.name + " Stats (Level: " + str(self.level) +
" Health: " + str(self.hitpoints) +
" ATK: " + str(self.hitpoints) + ")")
class Game(object):
def __init__(self, starting_level=1):
self.player = Player(starting_level)
# create monster
self.monster = Monster(level=self.player.level - 1, name='Goblin')
def battle(self, player, monster):
print("A {} engages you in battle!".format(monster.name))
monster.take_damage(player.attack_damage)
print("You dealt " + str(player.attack_damage) + " damage to the goblin!")
self.player.take_damage(monster.attack_damage)
print("The goblin struck back with " + str(monster.attack_damage) + " damage!")
def act(self):
# print stats
self.player.print_stats()
self.monster.print_stats()
# show menu
menu = 'Attack', 'Block', 'Use Item'
print(menu)
print("\nWhat will you do?: ")
action = input()
# take an action
if action == 'Attack':
self.battle(self.player, self.monster)
def main():
game = Game(starting_level=3)
while(True):
game.act()
if __name__ == '__main__':
main()

Resources