conditional statements causes syntax errors in python codes [closed] - python

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 6 months ago.
Improve this question
import traceback
def calculator():
# Get dog age
age = input("Input dog years: ")
try:
# Cast to float
dage = float(age)
if dage > 0:
if dage <= 1:
print ("The given dog age " + str(dage) + " is " + str(round(dage * 15) ) + " in human years")
elif 1 < dage <= 2:
print ("The given dog age " + str(dage) + " is " + str(round(dage * 12) ) + " in human years")
elif 2 < dage <= 3 :
print ("The given dog age " + str(dage) + " is " + str(round(dage * 9.3) ) + " in human years")
elif 3 < dage <= 4 :
print ("The given dog age " + str(dage) + " is " + str(round(dage * 8) ) + " in human years")
elif 4 < dage <= 5 :
print ("The given dog age " + str(dage) + " is " + str(round(dage * 7.2) ) + " in human years")
elif 5 < dage :
print ("The given dog age " + str(dage) + " is " + str(36 + 7 * (round(dage - 5.0)) + " in human years")
else:
print ("your input should be a positive number")
except:
print(age, "is an invalid age.")
print(traceback.format_exc())
calculator() # This line calls the calculator function
this code calculates the age of a dog in human years
but when it was executed, there was an error in the 24th line (else:)

There is a missing parenthesis in
elif 5 < dage :
print("The given dog age " + str(dage) + " is " + str(36 + 7 * (round(dage - 5.0)) + " in human years")
Add one more parenthesis at the end of print statement

Solution to your issue: Your code is missing a closing bracket for str() function in the print statement for your last elif. Here is the correct statement:
elif 5 < dage :
print ("The given dog age " + str(dage) + " is " + str(36 + 7 * (round(dage - 5.0))) + " in human years")
Improvements: You can also use f-strings to improve readability. See this tutorial for more details. Also, you can simplify the conditions in your elif statements as the lower bound is not needed.
Here is the code using f-strings and with some improvements:
def calculator():
age = input('Input dog years: ')
try:
dage = float(age)
if dage > 0:
msg = f'The given dog age {dage} is '
if dage <= 1:
msg += f'{dage * 15:.2f}'
elif dage <= 2:
msg += f'{dage * 12:.2f}'
elif dage <= 3 :
msg += f'{dage * 9.3:.2f}'
elif dage <= 4:
msg += f'{dage * 8:.2f}'
elif dage <= 5 :
msg += f'{dage * 7.2:.2f}'
else:
msg += f'{36 + 7 * (dage - 5.0):.2f}'
msg += ' in human years'
print(msg)
else:
print('your input should be a positive number')
except:
print(f'{age} is an invalid age.')
calculator()

You were missing a bracket on the last print in the else clause.
This is the correct code:
import traceback
def calculator():
# Get dog age
age = input("Input dog years: ")
try:
# Cast to float
dage = float(age)
if dage > 0:
if dage <= 1:
print ("The given dog age " + str(dage) + " is " + str(round(dage * 15) ) + " in human years")
elif 1 < dage <= 2:
print ("The given dog age " + str(dage) + " is " + str(round(dage * 12) ) + " in human years")
elif 2 < dage <= 3 :
print ("The given dog age " + str(dage) + " is " + str(round(dage * 9.3) ) + " in human years")
elif 3 < dage <= 4 :
print ("The given dog age " + str(dage) + " is " + str(round(dage * 8) ) + " in human years")
elif 4 < dage <= 5 :
print ("The given dog age " + str(dage) + " is " + str(round(dage * 7.2) ) + " in human years")
elif 5 < dage :
print ("The given dog age " + str(dage) + " is " + str(36 + 7 * (round(dage - 5.0)) + " in human years"))
else:
print ("your input should be a positive number")
except:
print(age, "is an invalid age.")
print(traceback.format_exc())
calculator() # This line calls the calculator function

Related

How can I make a "list(range)" work when the quantity is not valid?

So, i'm new to python and trying to learn it, i've watched some clips on youtube and came up with this, but the last part to check in the quantity is or is not in the list range is not working....
print ("Hello, my name is Dave, welcome to our coffe shop!!")
name = input ("What is your name?\n")
print("Hello " + name + ", thank you for comming to our coffe shop!")
print ("What can i get you ?")
menu = str("caffe latte, " + "tea, " + "black coffe")
menu_choice = ["caffe latte","tea","black coffe"]
choice1 = input() # anything
print ("This is our menu:")
print (menu)
unavailable = True
# order loop for the coffe
while unavailable:
order = input ()
if order in menu_choice:
unavailable = False
print ("And how many " + order + " would you like?")
else:
print ("Sorry we dont have " + order + ", this is our menu :\n" + menu)
if order == "caffe latte":
price = 13
elif order == "tea":
price = 9
elif order == "black coffe":
price = 15
#quantity loop
list(range(1, 10))
#here is the problem i'm having RN, the part with if not in in list is skipped
choice_number = True
while choice_number:
quantity = input()
total = price * int(quantity)
if quantity not in {list} :
choice_number = False
if quantity == "1" :
print ("Alright " + name, "that will be " + str(total) +"$,", "a", order + " comming at you!")
elif quantity >= "2" :
print ("Alright " + name, "that will be " + str(total) +"$,", quantity + " " + order + " comming at you!")
else:
print ("Quantity invalid, please select a number from 1 to 10.")
Assign this list(range(1, 10)) in a variable like qty_lst = list(range(1, 10)).
or you can simnply write:
if quantity not in list(range(1, 10)):
quantity = input("Enter Quantity")
total = price * int(quantity)
if quantity not in range(1,10) :
print ("Quantity invalid, please select a number from 1 to 10.")
else:
if quantity == "1":
print("Alright " + name, "that will be " + str(total) + "$,", "a", order + " comming at you!")
elif quantity >= "2":
print("Alright " + name, "that will be " + str(total) + "$,", quantity + " " + order + " comming at you!")
I would recommend getting rid of the listed range and just doing it like this, also you don't need a while True loop its not really needed
if quantity < 1 or quantity > 10:
# not in range
else:
# in range
Dont use if ... in range(), i'm not sure about this, but i think that doing so, python will not know that the sequence is in order and will check your value against all the sequence.
If i'm wrong, let's say i learned something :D

NameError: name 'mNewCal' is not defined issue

Im having some issue with my code. Im not really sure what's wrong with it. Thank you
if mNewCal or fNewCal < 1200:
NameError: name 'mNewCal' is not defined
sorry if the format is a little weird, stack overflow made it weird.
gender = int(input("enter your gender as a number from the following \n Male: 1 \n Female: 2 \n " ))
height = int(input("Please enter your height in inches: "))
age = int(input("Please enter your age: "))
weight = int(input("Enter your weight in lbs: "))
exercise = int(input("How much exercise do you do during the week (enter number) \n little to no: 1 \n light: 2 \n moderate: 3 \n heavy: 4 \n "))
if gender == 1:
mBMR = 66 + (6.3 * weight) + (12.9 * height) - (6.8 * age)
elif gender == 2:
fBMR = 655 + (4.3 * weight) + (4.7 * height) - (4.7 * age)
if gender == 1:
if exercise == 1:
cal = mBMR * 1.2
elif exercise == 2:
cal = mBMR * 1.375
elif exercise == 3:
cal = mBMR * 1.55
elif exercise == 4:
cal = mBMR * 1.8
else:
if exercise == 1:
cal = fBMR * 1.2
elif exercise == 2:
cal = fBMR * 1.375
elif exercise == 3:
cal = fBMR * 1.55
elif exercise == 4:
cal = fBMR * 1.8
if gender == 1:
mTotalCal = mBMR * 1.2
#print(mTotalCal)
else:
fTotalCal = fBMR * 1.2
# print(fTotalCal)
looseWeight = str(input("do you want to loose weight? if yes, enter Y: \n if no enter N: \n "))
if looseWeight == "Y":
yesWeight = int(input("How much weight do you want to loose (lbs) ? "))
else:
print("thank you for using Nakul Industries health program!")
weeks = yesWeight
days = weeks * 7
months = days / 30
if gender == 1:
mNewCal = mTotalCal - 500
else:
fNewCal = fTotalCal - 500
if mNewCal or fNewCal < 1200:
print("WARNING! your total intake will be less then 1200 calories, please consult a doctor before following this.")
print("In order to lose " + yesWeight + " ,it will take " + weeks + " weeks " + "\n" + "or " + days + " days" + "\n or " + "approximately " + months + " months.")
else:
print(
"In order to lose " + yesWeight + " ,it will take " + weeks + " weeks " + "\n" + "or " + days + " days" + "\n or " + "approximately " + months + " months.")
You only define fNewCal or mNewCal and have both in an or statement, if you haven't defined one of the variables and it's checked by the if statement it will raise a NameError like this. You should just use one variable, like newCal, and determine whether it's female or male using the existing gender variable like this:
gender = int(input("enter your gender as a number from the following \n Male: 1 \n Female: 2 \n "))
height = int(input("Please enter your height in inches: "))
age = int(input("Please enter your age: "))
weight = int(input("Enter your weight in lbs: "))
exercise = int(input(
"How much exercise do you do during the week (enter number) \n little to no: 1 \n light: 2 \n moderate: 3 \n heavy: 4 \n "))
if gender == 1:
mBMR = 66 + (6.3 * weight) + (12.9 * height) - (6.8 * age)
elif gender == 2:
fBMR = 655 + (4.3 * weight) + (4.7 * height) - (4.7 * age)
if gender == 1:
if exercise == 1:
cal = mBMR * 1.2
elif exercise == 2:
cal = mBMR * 1.375
elif exercise == 3:
cal = mBMR * 1.55
elif exercise == 4:
cal = mBMR * 1.8
else:
if exercise == 1:
cal = fBMR * 1.2
elif exercise == 2:
cal = fBMR * 1.375
elif exercise == 3:
cal = fBMR * 1.55
elif exercise == 4:
cal = fBMR * 1.8
if gender == 1:
mTotalCal = mBMR * 1.2
# print(mTotalCal)
else:
fTotalCal = fBMR * 1.2
# print(fTotalCal)
looseWeight = str(input("do you want to loose weight? if yes, enter Y: \n if no enter N: \n "))
if looseWeight == "Y":
yesWeight = int(input("How much weight do you want to loose (lbs) ? "))
else:
print("thank you for using Nakul Industries health program!")
weeks = yesWeight
days = weeks * 7
months = days / 30
if gender == 1:
newCal = mTotalCal - 500
else:
newCal = fTotalCal - 500
if newCal < 1200:
print("WARNING! your total intake will be less then 1200 calories, please consult a doctor before following this.")
print(
"In order to lose " + yesWeight + " ,it will take " + weeks + " weeks " + "\n" + "or " + days + " days" + "\n or " + "approximately " + months + " months.")
else:
print(
"In order to lose " + yesWeight + " ,it will take " + weeks + " weeks " + "\n" + "or " + days + " days" + "\n or " + "approximately " + months + " months.")
In general, since you already have a gender variable, there's no reason to sex your other variables, either, though the remaining ones currently won't break the program because they are all contingent on gender. Here it is without the pointlessly sexed variables, it will work fine this way:
gender = int(input("enter your gender as a number from the following \n Male: 1 \n Female: 2 \n "))
height = int(input("Please enter your height in inches: "))
age = int(input("Please enter your age: "))
weight = int(input("Enter your weight in lbs: "))
exercise = int(input(
"How much exercise do you do during the week (enter number) \n little to no: 1 \n light: 2 \n moderate: 3 \n heavy: 4 \n "))
if gender == 1:
BMR = 66 + (6.3 * weight) + (12.9 * height) - (6.8 * age)
elif gender == 2:
BMR = 655 + (4.3 * weight) + (4.7 * height) - (4.7 * age)
if gender == 1:
if exercise == 1:
cal = BMR * 1.2
elif exercise == 2:
cal = BMR * 1.375
elif exercise == 3:
cal = BMR * 1.55
elif exercise == 4:
cal = BMR * 1.8
else:
if exercise == 1:
cal = BMR * 1.2
elif exercise == 2:
cal = BMR * 1.375
elif exercise == 3:
cal = BMR * 1.55
elif exercise == 4:
cal = BMR * 1.8
if gender == 1:
TotalCal = BMR * 1.2
# print(mTotalCal)
else:
TotalCal = BMR * 1.2
# print(fTotalCal)
loseWeight = str(input("do you want to loose weight? if yes, enter Y: \n if no enter N: \n "))
if loseWeight == "Y":
yesWeight = int(input("How much weight do you want to loose (lbs) ? "))
else:
print("thank you for using Nakul Industries health program!")
weeks = yesWeight
days = weeks * 7
months = days / 30
if gender == 1:
newCal = TotalCal - 500
else:
newCal = TotalCal - 500
if newCal < 1200:
print("WARNING! your total intake will be less then 1200 calories, please consult a doctor before following this.")
print(
"In order to lose " + yesWeight + " ,it will take " + weeks + " weeks " + "\n" + "or " + days + " days" + "\n or " + "approximately " + months + " months.")
else:
print(
"In order to lose " + yesWeight + " ,it will take " + weeks + " weeks " + "\n" + "or " + days + " days" + "\n or " + "approximately " + months + " months.")

Why is it that the list variables in this code gets values in them backwards? HP is the last assigned variable despite being there first in the list

I'm making a simple program (I am a beginner at python) where I fight a monster with random assigned values. I used 2 lists with 4 variables each depicting hp atk def and spd. They get assigned a random number of 10 to 15 and get multiplied by 2. I don't really know what I am doing wrong here.
import random
monsters = ["slime","goblin","troll","dryad","bard","clown"]
hp,atk,dfn,spd = 0,0,0,0
mhp,matk,mdfn,mspd = 0,0,0,0
stats = [hp,atk,dfn,spd]
mstats = [hp,atk,dfn,spd]
damage = 0
defend = 0
action = "none"
name = input()
print("Your name is " + name + ", time to battle!")
for x in stats:
stats[x] = random.randint(10,15) * 2
print("Your stats(hp/a/d/s): " + str(stats[x]))
for y in mstats:
mstats[y] = random.randint(10,15) * 2
print("Monster stats(hp/a/d/s): " + str(mstats[y]))
while stats[hp] > 0 or mstats[hp] > 0:
print("What will you do? 1 for attack, 2 for defend, others to give up")
action = input()
if action == "1":
damage = stats[atk] / 2 + random.randint(1,5)
mstats[hp] = mstats[hp] - damage
print("You slash the monster for " + str(damage) + " damage!" )
print("Monster HP: " + str(mstats[hp]))
damage = mstats[atk] / 2
stats[hp] = stats[hp] - damage
print("The monster slashes you for " + str(damage) + " damage!")
print("Your HP: " + str(stats[hp]))
if action == "2":
damage = mstats[atk] / 2 - random.randint(3,5)
if damage > 0:
stats[hp] = stats[hp] - damage
print("The monster slashes you for " + str(damage) + " damage!")
print("Your HP: " + str(stats[hp]))
if action != "1" and action != "2":
stats[hp] = 0
if stats[hp] < 0 or stats[hp] == 0:
print("You lose!")
if mstats[hp] < 0:
print("You win!")
Hopefully this code isn't a mess, I thank you all in advance if extra corrections can be given.

Unsupported operand types for: 'str' and 'str' [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 3 years ago.
Improve this question
def Rounds():
P1Roll1 = (random.randint(1,7))
P1Roll2 = (random.randint(1,7))
Sum1 = P1Roll1 + P1Roll2
Dice = input("Player 1's turn. Do you want to roll your 2 dice? (Y for yes
and N for no) ")
if Dice == "Y" or Dice == "y":
print("Player 1 rolled their 2 dice. They rolled a " + str(P1Roll1) + " and a " + str(P1Roll2) + " which totals to " + str(Sum1))
if int(Sum1) % 2 == 0:
print("Player 1 got 10 more points for rolling an even sum. " + "\n" + "Player 1 got " + str(Sum1 + 10) + " points")
Final1 = str(Sum1 + 10)
elif int(Sum1) % 2 == 1:
print("Player 1 got " + str(Sum1) + " points")
Final1 = str(Sum1)
elif Dice == "N" or Dice == "n":
sys.exit()
P2Roll1 = (random.randint(1,7))
P2Roll2 = (random.randint(1,7))
Sum2 = P2Roll1 + P2Roll2
Dice1 = input("Player 2's turn. Do you want to roll your 2 dice? (Y for yes and N for no) ")
if Dice1 == "Y" or "y":
print("Player 2 rolled their 2 dice. They rolled a " + str(P2Roll1) + " and a " + str(P2Roll2) + " which totals to " + str(Sum2))
if int(Sum2) % 2 == 0:
print("Player 2 got 10 more points for rolling an even sum. " + "\n" + "Player 2 got " + str(Sum2 + 10) + " points")
Final2 = str(Sum2 + 10)
elif int(Sum2) % 2 == 1:
print("Player 2 got " + str(Sum2) + " points")
Final2 = str(Sum2)
elif Dice1 == "N" or "n":
sys.exit()
if Final2 > Final1:
print("Player 2 won round 1 by " + (Final2 - Final1) + " points")
elif Final1 > Final2:
print("Player 1 won round 1 by " + (Final1 - Final2) + "points")
elif Final1 == Final2:
print("Round 1 was a draw as both players got " + str(Final1) + " points")
When this function is run I get an unsupported operand error. I have tried putting str() and int() in but it gives other errors such as "not all arguments converted during string formatting".
The full error code is:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
Rounds()
File "C:\Users\jacobryan_000\Downloads\Dicegame############# (1).py", line 124, in Rounds
print("Player 2 won round 1 by " + (Final2 - Final1) + " points")
TypeError: unsupported operand type(s) for -: 'str' and 'str'
In line 124, you should convert into int to make a subtraction. Then change into str to print:
if Final2 > Final1:
print("Player 2 won round 1 by " + str(int(Final2) - int(Final1)) + " points")
elif Final1 > Final2:
print("Player 1 won round 1 by " + str(int(Final1) - int(Final2)) + " points")

Getting a TypeError: Can't convert 'float' object to str implicitly?

this is part of my GCSE computing code project and i cant get it to work properly please help me.
it is meant to be a 'Encounter' game between two characters
import random
tryagain = "Y" or "y"
char1name = input(str("character 1 please enter your name "))
char2name = input(str("character 2 please enter your name "))
print ("Player 1, your name is " + char1name)
print ("Player 2, your name is " + char2name)
print (" ")
player1skill = input(str("what is your skill level " + char1name + "? "))
player2skill = input(str("what is your skill level " + char2name + "? "))
player1strength = input(str("what is your strength level " + char1name + "? "))
player2strength = input(str("what is your strength level " + char2name + "? "))
print (char1name + " has a skill of " + player1skill + " and a strength of " + player1strength)
print (char2name + " has a skill of " + player2skill + " and a strength of " + player2strength)
if (int(player1strength) >= int(player2strength)):
strength_modifier = ((int(player1strength)) - (int(player2strength)))
else:
strength_modifier = (int(player2strength) - (int(player1strength)))
if (int(player1skill) >= int(player2skill)):
skill_modifier = ((int(player1skill)) - (int(player2skill)))
else:
skill_modifier = (int(player2skill) - (int(player1skill)))
print("The strength modifier is " + (int(strength_modifier) / (int(5))))
print("The skill modifier is " + (int(skill_modifier) // (int(5))))
roll_player1 = random.randint(1,6)
roll_player2 = random.randint(1,6)
if int(roll_player1) == int(roll_player2):
print("no changes are made")
else: print(char1name +"'s skill has gone up to " + (str(player1skill) + str(skill_modifier)))
print("and their strength has gone up to" + (int(player1strength) + int(strength_modifier)))
if int(roll_player1) <= int(roll_player2):
print(char2name + "'s skill has gone up to " + (int(player2skill) + int(skill_modifier)))
print("and their strength has gone up to" + (int(player2strength) + int(strength_modifier)))
this is the error i keep getting, what is the problem??
character 1 please enter your name player1
character 2 please enter your name player2
Player 1, your name is player1
Player 2, your name is player2
what is your skill level player1? 10
what is your skill level player2? 5
what is your strength level player1? 20
what is your strength level player2? 10
player1 has a skill of 10 and a strength of 20
player2 has a skill of 5 and a strength of 10
Traceback (most recent call last):
File "\\fileserver-01\studenthome$\*serverlocation*
line 29, in <module>
print("The strength modifier is " + (int(strength_modifier) / (int(5))))
TypeError: Can't convert 'float' object to str implicitly
The result of this operation:
(int(strength_modifier) / (int(5)))
Is a float. To change it into a string, just convert it to string.
str(int(strength_modifier) / (int(5)))

Categories