I have this function:
def damage_rate(hurricanes):
damage_scale = {0: 0,
1: 100000000,
2: 1000000000,
3: 10000000000,
4: 50000000000}
hurricanes_by_damage = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[]}
for cane in hurricanes:
total_damage = hurricanes[cane]['Damage']
if total_damage == "Damages not recorded":
hurricanes_by_damage[0].append(hurricanes[cane])
elif total_damage == damage_scale[0]:
hurricanes_by_damage[0].append(hurricanes[cane])
elif total_damage > damage_scale[0] and total_damage <= damage_scale[1]:
hurricanes_by_damage[1].append(hurricanes[cane])
elif total_damage > damage_scale[1] and total_damage <= damage_scale[2]:
hurricanes_by_damage[2].append(hurricanes[cane])
elif total_damage > damage_scale[2] and total_damage <= damage_scale[3]:
hurricanes_by_damage[3].append(hurricanes[cane])
elif total_damage > damage_scale[3] and total_damage <= damage_scale[4]:
hurricanes_by_damage[4].append(hurricanes[cane])
elif total_damage > damage_scale[4]:
hurricanes_by_damage[5].append(hurricanes[cane])
return hurricanes_by_damage
But when I try to print it in Jupyter, it keeps telling me that '>' is not supported between str and int.
I already tried a different method of ignoring the str in the library with pass but it didn't work either.
Convert the value to int before comparing and it should resolve the issue.
Keep in mind the edge cases where the value is not a numeric value other than "Damaged not recorded" would throw another error that needs to be handled.
In your case, the simple fix would be:
def damage_rate(hurricanes):
damage_scale = {0: 0,
1: 100000000,
2: 1000000000,
3: 10000000000,
4: 50000000000}
hurricanes_by_damage = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[]}
for cane in hurricanes:
total_damage = hurricanes[cane]['Damage']
if total_damage == "Damages not recorded":
hurricanes_by_damage[0].append(hurricanes[cane])
else:
try:
total_damage = int(total_damage) #converting to integer to compare
except Exception as E:
print(E)
print(f"Cant convert '{total_damage}' to int") #add code to handle error here
if total_damage == damage_scale[0]:
hurricanes_by_damage[0].append(hurricanes[cane])
elif total_damage > damage_scale[0] and total_damage <= damage_scale[1]:
hurricanes_by_damage[1].append(hurricanes[cane])
elif total_damage > damage_scale[1] and total_damage <= damage_scale[2]:
hurricanes_by_damage[2].append(hurricanes[cane])
elif total_damage > damage_scale[2] and total_damage <= damage_scale[3]:
hurricanes_by_damage[3].append(hurricanes[cane])
elif total_damage > damage_scale[3] and total_damage <= damage_scale[4]:
hurricanes_by_damage[4].append(hurricanes[cane])
elif total_damage > damage_scale[4]:
hurricanes_by_damage[5].append(hurricanes[cane])
return hurricanes_by_damage
Related
Why wouldn't my for loop work? If I put in 0.85 for grade score it'd print out F and error message instead of B. Why is this?
grade=input('Score Grade:')
fg=float(grade)
for fg in range(0,1):
if fg >= 0.9:
print('A')
elif fg>=0.8:
print('B')
elif fg>=0.7:
print('C')
elif fg>=0.6:
print('D')
else:
print('F')
print('error grade out of range')
quit()
You are misusing the range() function. range() is used to iterate over multiple values, not to validate if a number is in a range. You should instead check that fg greater than or equal to 0, or less than or equal to 1. Like this:
grade=input('Score Grade:')
fg=float(grade)
if 0 > fg or 1 < fg:
print('error grade out of range')
quit()
if fg >= 0.9:
print('A')
elif fg>=0.8:
print('B')
elif fg>=0.7:
print('C')
elif fg>=0.6:
print('D')
else:
print('F')
you are doing this for one time you dont need to use a loop
you can do this
grade = float(input('Score Grade:'))
if grade < 1 and grade > 0:
if grade > 0.9:
print('A')
elif grade >= 0.8:
print('B')
elif grade >= 0.7:
print('C')
elif grade >= 0.6:
print('D')
elif grade < 0.6:
print('F')
else:
print('error grade out of range')
quit()
You do not need to use for operator neither range. The simplest solution is:
'''
grade = input("Enter number:")
try:
grade = float(grade)
except:
grade = -1
if grade >= 0.9:
print("A")
elif grade >= 0.8:
print("B")
elif grade >= 0.7:
print("C")
elif grade >= 0.6:
print("D")
elif grade < 0.6:
print("F")
else:
print("Error!")
quit()
'''
So yea, im making an RPG and the battle isnt too reliable... if you can figure out why then that would be great!
#Enemy System
def MMEnemy(PL, HP, STR, DEF, SLTH, Name, CLASSNO):
EnemyLvl = random.randint(PL, (PL * 2))
EnemyHP = random.randint(EnemyLvl * 40, EnemyLvl * 80)
Defend = False
while HP >= 1 & EnemyHP >= 1:
HPPercent = HP / PL
HPPercent = int(HPPercent)
if HPPercent >= 90:
HealthBar = ("█████████▓ | ", HP, " / ",(100 * PL))
elif HPPercent >= 80 and HPPercent <= 89:
HealthBar = ("████████▓░ | ", HP, " / ",(100 * PL))
elif HPPercent >= 70 and HPPercent <= 79:
HealthBar = ("███████▓░░ | ", HP, " / ",(100 * PL))
elif HPPercent >= 60 and HPPercent <= 69:
HealthBar = ("██████▓░░░ | ", HP, " / ",(100 * PL))
elif HPPercent >= 50 and HPPercent <= 59:
HealthBar = ("█████▓░░░░ | ", HP, " / ",(100 * PL))
elif HPPercent >= 40 and HPPercent <= 49:
HealthBar = ("████▓░░░░░ | ", HP, " / ",(100 * PL))
elif HPPercent >= 30 and HPPercent <= 39:
HealthBar = ("███▓░░░░░░ | ", HP, " / ",(100 * PL))
elif HPPercent >= 20 and HPPercent <= 29:
HealthBar = ("██▓░░░░░░░ | ", HP, " / ",(100 * PL))
elif HPPercent >= 10 and HPPercent <= 19:
HealthBar = ("█▓░░░░░░░░ | ", HP, " / ",(100 * PL))
elif HPPercent >= 0 and HPPercent <= 9:
HealthBar = ("▓░░░░░░░░░ | ", HP, " / ",(100 * PL))
else:
HealthBar = "Unknown Health!!"
print("The ", Name," is still standing... (", HealthBar, " HP)")
print("What should you do?")
print("1: Attack\n2: Heal\n3: Defend\n4: Run")
choice = input()
choice = int(choice)
if choice == 1:
roll = random.randint(STR, STR + 2)
print("You attack for ", roll)
EnemyHP -= (roll)
print(Name, " is at ", EnemyHP)
elif choice == 2:
roll = random.randint(PL * -2, PL * 5)
if CLASSNO == 2:
roll += PL * 3
if roll >= 1:
print("You healed for ", roll)
if roll <= 0:
print("You failed your heal [", roll," HP]")
HP += roll
elif choice == 3:
Defend = True
elif choice == 4:
print("Run failed, not implemented yet")
else:
print("None were chosen, you stood still")
DamageTaken = random.randint(5, EnemyLvl * 8)
if Defend == True:
prin("Your Defend was successful")
Defend = False
else:
HP -= DamageTaken
DamageTaken = str(DamageTaken)
print("You got damaged for ", DamageTaken,"!")
if HP <= 0:
print("You have been defeated by the ", Name,"...")
return "Lose"
if EnemyHP <= 0:
print("You defeated ", Name,"!")
return "Win"
CLASSNO = 1
level = 1
Strength = 5
Defence = 5
Stealth = 5
HP = 100
GameEnd = False
battle = MMEnemy(level, HP, Strength, Defence, Stealth, "Irc", CLASSNO)
battle = str(battle)
if battle != "Win" or battle != "Lose":
while battle != "Win" or battle != "Lose":
print("Restarted")
battle = MMEnemy(level, HP, Strength, Defence, Stealth, "Irc", CLASSNO)
battle = str(battle)
if battle == "Win":
print("Battle Won")
GameEnd = True
elif battle == "Lose":
print("Battle lost")
GameEnd = True
else:
print("Nothing Worked")
Ive tried changing the flags for the loop and simplifying it but it doesnt seem to do much. Its supposed to load and put you into battle but it stops halfway without returning anything making it so it wont get out of the loop
Wanted to suggest an improvement to the code, and was having trouble posting the code in the comments, so here it is:
hp_string = ""
if HPPercent > 0:
full_hp = "█"
current_hp = "▓"
used_hp = "░"
for i in range(int((HPPercent-HPPercent % 10)/10)):
hp_string += full_hp
hp_string += current_hp
if HPPercent <= 90:
for i in range(9 - int((HPPercent-HPPercent % 10)/10)):
hp_string += used_hp
HealthBar = (hp_string + " | ", HP, " / ",(100 * PL))
else:
HealthBar = "Unknown Health!!"
Also, as someone mentioned in the comments, & is not the same as and in python.
It's me again, from like an hour ago.
So I was messing around with some of the answers that I was provided with and well this is what I got now:
import random
while != "No":
print("Would you like to get your set?")
choice = input("Yes or No: ")
if choice == 'Yes:
print(swimming())
else:
break
def swimming():
def stroke():
x = random.randint(1, 150)
if x < 51:
print("Freestyle")
elif x >51 and x<100:
print("Breaststroke")
else:
print("Butterfly")
def laps():
i = random.randint(1, 300)
if i <= 99:
print("Ten Laps")
elif i >=100 and i <= 199:
print("Fifteen Laps")
else:
print("Twenty Laps")
def style():
j = random.randint(0,15)
if j < 5:
print("Paddles")
elif j > 6 and j < 10:
print("Bouy")
else:
print("Kick-Board")
I currently get an error in my command line saying that "!=" is an invalid syntax and can not be run.
Would this code at all work or is there something I can do to fix it?
Sorry about my code, I barely started to learn it a week ago.
while != "No":
is an incomplete condition, you need to change it to something like:
while True: # so the loop only ends/breaks on a condition inside it
Also, You have a missing ' in the line:
if choice == 'Yes:
Change it to:
if choice == 'Yes':
EDIT:
you need to define the swimming() method before the loop:
import random
def swimming():
def stroke():
x = random.randint(1, 150)
if x < 51:
print("Freestyle")
elif x >51 and x<100:
print("Breaststroke")
else:
print("Butterfly")
def laps():
i = random.randint(1, 300)
if i <= 99:
print("Ten Laps")
elif i >=100 and i <= 199:
print("Fifteen Laps")
else:
print("Twenty Laps")
def style():
j = random.randint(0,15)
if j < 5:
print("Paddles")
elif j > 6 and j < 10:
print("Bouy")
else:
print("Kick-Board")
while True:
print("Would you like to get your set?")
choice = input("Yes or No: ")
if choice == 'Yes':
print(swimming())
else:
break
Also, this would return None as you are not calling any method inside the swimming() method or returning anything.
So you can call the methods inside like:
def swimming():
def stroke():
x = random.randint(1, 150)
if x < 51:
print("Freestyle")
elif x >51 and x<100:
print("Breaststroke")
else:
print("Butterfly")
def laps():
i = random.randint(1, 300)
if i <= 99:
print("Ten Laps")
elif i >=100 and i <= 199:
print("Fifteen Laps")
else:
print("Twenty Laps")
def style():
j = random.randint(0,15)
if j < 5:
print("Paddles")
elif j > 6 and j < 10:
print("Bouy")
else:
print("Kick-Board")
stroke()
laps()
style()
Is this what you want?
import random
def swimming():
def stroke():
x = random.randint(1, 150)
if x < 51:
print("Freestyle")
elif x >51 and x<100:
print("Breaststroke")
else:
print("Butterfly")
def laps():
i = random.randint(1, 300)
if i <= 99:
print("Ten Laps")
elif i >=100 and i <= 199:
print("Fifteen Laps")
else:
print("Twenty Laps")
def style():
j = random.randint(0,15)
if j < 5:
print("Paddles")
elif j > 6 and j < 10:
print("Bouy")
else:
print("Kick-Board")
stroke()
laps()
style()
while True:
print("Would you like to get your set?")
choice = input("Yes or No: ")
if choice == 'Yes':
swimming()
else:
break
I currently am making a blackjack python minigame, where a player plays until he gets a blackjack or stands and returns the value of his deck. This game does not play against a dealer and instead just uses his hands as a score. My problem is, I cannot figure out a way to make aces go from 11 to 1 without looping and breaking the program. Here is my code:
import random
def play():
output = "Your hand: "
player = []
total=0
count = 0
while len(player) != 2:
card = random.randint(1,52)
if card <= 4:
output += "A "
total += 11
player.append("A")
elif card <= 8:
output+="2 "
total+=2
player.append("2")
elif card <= 12:
output+="3 "
total+=3
player.append("3")
elif card <= 16:
output+="4 "
total+=4
player.append("4")
elif card <= 20:
output+="5 "
total+=5
player.append("5")
elif card <= 24:
output+="6 "
total+=6
player.append("6")
elif card <= 28:
output+="7 "
total+=7
player.append("7")
elif card <= 32:
output+="8 "
total+=8
player.append("8")
elif card <= 36:
output+="9 "
total+=9
player.append("9")
elif card <= 40:
output+="10 "
total+=10
player.append("10")
elif card <= 44:
output+="J "
total+=10
player.append("J")
elif card <= 48:
output+="Q "
total+=10
player.append("Q")
elif card <= 52:
output+= "K "
total+=10
player.append("K")
if len(player) == 2:
print(f"{output} ({total}) ")
while len(player) >= 2:
action_taken = input("Would you like to 'hit' or 'stand': ")
if action_taken == "hit":
card = random.randint(1,52)
if card <= 4:
output += "A "
total += 11
player.append("A")
elif card <= 8:
output+="2 "
total+=2
player.append("2")
elif card <= 12:
output+="3 "
total+=3
player.append("3")
elif card <= 16:
output+="4 "
total+=4
player.append("4")
elif card <= 20:
output+="5 "
total+=5
player.append("5")
elif card <= 24:
output+="6 "
total+=6
player.append("6")
elif card <= 28:
output+="7 "
total+=7
player.append("7")
elif card <= 32:
output+="8 "
total+=8
player.append("8")
elif card <= 36:
output+="9 "
total+=9
player.append("9")
elif card <= 40:
output+="10 "
total+=10
player.append("10")
elif card <= 44:
output+="J "
total+=10
player.append("J")
elif card <= 48:
output+="Q "
total+=10
player.append("Q")
elif card <= 52:
output+= "K "
total+=10
player.append("K")
if len(player) >= 2 and total <=21:
print(f"{output} ({total}) ")
if total > 21:
if "A" in player: #Ask why ace always messes up
if count < 1:
count +=1
total-=10
print(f"{output} ({total}) ")
if player.count("A") > 1:
total -= 10
print(f"{output} ({total}) ")
else:
print(f"{output} ({total}) ")
print("BUST!")
return total
if action_taken == "stand":
return total
if action_taken != "hit" or "stand":
print("Enter a valid input ('hit' or 'stand') ")
play()
if "A" in player will always be True once there's an ace in the deck, and so you never get to the else where you print "BUST!" and return, so the loop just continues. You can do something like incremeting count for every ace in the deck and then change the ace part to be:
if total > 21:
player_aces = player.count("A") # How many aces the player has
if player_aces != count: # Meaning there are aces that weren't checked
for _ in range(player_aces - count):
total -= 10 # Could also be simplified to: total -= 10 * (player_aces - count)
count = player_aces
print(f"{output} ({total}) ")
else:
print(f"{output} ({total}) ")
print("BUST!")
return total
Also, if action_taken != "hit" or "stand" doesn't check that action_taken is not "hit" and not "stand". An or treats both its inputs as bool values and returns whether at least one is True. The != operator has precedence over or, so the line is actually if (action_taken != "hit") or "stand". The left part of that does what it's supposed to do, but then the right part evaluates "stand" as a bool, and in python every non-empty string is evaluated as True. So the right expression is always True, and so is the or - and the program will always enter the if statement.
You probably want: if action_taken != "hit" and action_taken != "stand".
There were a coupe of issues that I have fixed. I have created a counter for the number of Aces, this allows us to count how many times we can reduced the total by - otherwise we just keep removing 10.
Also the indentation of the last else statement needed moving out.
import random
def play():
output = "Your hand: "
player = []
total=0
count = 0
reducedA = 0
while len(player) != 2:
card = 1
#card = random.randint(1,52)
if card <= 4:
output += "A "
total += 11
reducedA+=1
player.append("A")
elif card <= 8:
output+="2 "
total+=2
player.append("2")
elif card <= 12:
output+="3 "
total+=3
player.append("3")
elif card <= 16:
output+="4 "
total+=4
player.append("4")
elif card <= 20:
output+="5 "
total+=5
player.append("5")
elif card <= 24:
output+="6 "
total+=6
player.append("6")
elif card <= 28:
output+="7 "
total+=7
player.append("7")
elif card <= 32:
output+="8 "
total+=8
player.append("8")
elif card <= 36:
output+="9 "
total+=9
player.append("9")
elif card <= 40:
output+="10 "
total+=10
player.append("10")
elif card <= 44:
output+="J "
total+=10
player.append("J")
elif card <= 48:
output+="Q "
total+=10
player.append("Q")
elif card <= 52:
output+= "K "
total+=10
player.append("K")
if len(player) == 2:
print(f"{output} ({total}) ")
while len(player) >= 2:
action_taken = input("Would you like to 'hit' or 'stand': ")
if action_taken == "hit":
card = random.randint(1,52)
if card <= 4:
output += "A "
total += 11
player.append("A")
reducedA += 1
elif card <= 8:
output+="2 "
total+=2
player.append("2")
elif card <= 12:
output+="3 "
total+=3
player.append("3")
elif card <= 16:
output+="4 "
total+=4
player.append("4")
elif card <= 20:
output+="5 "
total+=5
player.append("5")
elif card <= 24:
output+="6 "
total+=6
player.append("6")
elif card <= 28:
output+="7 "
total+=7
player.append("7")
elif card <= 32:
output+="8 "
total+=8
player.append("8")
elif card <= 36:
output+="9 "
total+=9
player.append("9")
elif card <= 40:
output+="10 "
total+=10
player.append("10")
elif card <= 44:
output+="J "
total+=10
player.append("J")
elif card <= 48:
output+="Q "
total+=10
player.append("Q")
elif card <= 52:
output+= "K "
total+=10
player.append("K")
if len(player) >= 2 and total <=21:
print(f"{output} ({total}) ")
if total > 21:
if "A" in player: #Ask why ace always messes up
if count < 1:
count +=1
total-=10
print(f"{output} ({total}) ")
if player.count("A") > 1 and reducedA:
total -= 10
reducedA -= 1
print(f"{output} ({total}) ")
else:
print(f"{output} ({total}) ")
print("BUST!")
return total
else:
print(f"{output} ({total}) ")
print("BUST!")
return total
if action_taken == "stand":
return total
if action_taken != "hit" or action_taken != "stand":
print("Enter a valid input ('hit' or 'stand') ")
play()
temp = 120
if temp > 85:
print "Hot"
elif temp > 100:
print "REALLY HOT!"
elif temp > 60:
print "Comfortable"
else:
print "Cold"
Python picks the first condition that is true, and the rest of the if..elif..else branches are skipped.
120 > 85 is true, so the first test passes and 'Hot' is printed. It doesn't matter that the second test also matches after that point.
Put the > 100 test first:
if temp > 100:
print "REALLY HOT!"
elif temp > 85:
print "Hot"
elif temp > 60:
print "Comfortable"
else:
print "Cold"
Alternatively, limit the tests to exclude the upper range:
if 100 >= temp > 85:
print "Hot"
elif temp > 100:
print "REALLY HOT!"
elif temp > 60:
print "Comfortable"
else:
print "Cold"