Trying to take two strings with values attached and subtract them - python

As shown, I have written this code and have assigned values for CASH and TOTAL. What I can not understand is why I get.....
"Traceback (most recent call last):
File "C:\Python27\Checkout Counter2.py", line 29, in
change = cash - total
TypeError: unsupported operand type(s) for -: 'str' and 'str'"
I've tried multiple ways to make this work, and I dont see any difference between that and when it finds the total.
print "Welcome to the checkout counter! How many items are you purchasing today?"
#NOI is number of items
NOI = int(raw_input())
productlist = []
pricelist=[]
for counter in range(NOI):
print"Please enter the name of product", counter+1
productlist.append(raw_input())
print"And how much does", productlist[len(productlist)-1], "cost?"
pricelist.append(float(raw_input()))
if pricelist[len(pricelist)-1] < 0:
pricelist.pop()
productlist.pop()
len(productlist)-1
len(pricelist)-1
print "Your order was:"
subtotal=0.00
for counter in range(NOI):
print productlist[counter],
print "$%0.2f" % pricelist[counter]
subtotal += pricelist[counter]
total = "$%0.2f" % float(subtotal + (subtotal * .09))
print "Your subtotal comes to", "$" + str(subtotal) + ".", " With 9% sales tax, your total is " + str(total) + "."
print "Please enter cash amount:"
cash = raw_input()
while True:
change = cash - total
if cash < total:
print "You need to give more money to buy these items. Please try again."
else:
print "I owe you back", "$" + float(change)

"raw_input" will always return a string (even if you enter 3 or 3.5)
Therefore you have to:
cash = float(cash)
total = float(total)
Edit: Also, when you do:
total = "$%0.2f" % float(subtotal + (subtotal * .09))
total will also be a string, that is why you also have to convert it to float.
Hope it helps.

Related

I'm Havinig A TypeError in pygame [duplicate]

I'm writing a simple program to help generate orders for a game I'm a member of. It falls into the catergory of programmes I don't actually need. But now I've started I want it to work. It all pretty much runs smoothly but I can't figure out how to stop a type-error ocurring about half way through. Here's the code;
status = 1
print "[b][u]magic[/u][/b]"
while status == 1:
print " "
print "would you like to:"
print " "
print "1) add another spell"
print "2) end"
print " "
choice = input("Choose your option: ")
print " "
if choice == 1:
name = raw_input("What is the spell called?")
level = raw_input("What level of the spell are you trying to research?")
print "What tier is the spell: "
print " "
print "1) low"
print "2) mid"
print "3) high"
print " "
tier = input("Choose your option: ")
if tier == 1:
materials = 1 + (level * 1)
rp = 10 + (level * 5)
elif tier == 2:
materials = 2 + (level * 1.5)
rp = 10 + (level * 15)
elif tier == 3:
materials = 5 + (level * 2)
rp = 60 + (level * 40)
print "research ", name, "to level ", level, "--- material cost = ",
materials, "and research point cost =", rp
elif choice == 2:
status = 0
Can anyone help?
edit
The error I get is;
Traceback (most recent call last):
File "C:\Users\Mike\Documents\python\magic orders", line 27, in <module>
materials = 1 + (level * 1)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
A stacktrace would've helped, but presumably the error is:
materials = 1 + (level * 1)
‘level’ is a string, and you can't do arithmetic on strings. Python is a dynamically-typed language, but not a weakly-typed one.
level= raw_input('blah')
try:
level= int(level)
except ValueError:
# user put something non-numeric in, tell them off
In other parts of the program you are using input(), which will evaluate the entered string as Python, so for “1” will give you the number 1.
But! This is super-dangerous — imagine what happens if the user types “os.remove(filename)” instead of a number. Unless the user is only you and you don't care, never use input(). It will be going away in Python 3.0 (raw_input's behaviour will be renamed input).
Here is an example of a Type Error and how to fix it:
# Type Error: can only concatenate str (not "int") to str
name = "John"
age = 30
message = "My name is " + name + " and I am " + age + " years old."
# Fix:
message = "My name is " + name + " and I am " + str(age) + " years old."
In the above example, the error message says that we're trying to concatenate a string and an integer which is not possible. So, we need to convert the integer to string using str() function to fix the error.

First time getting this message 'IndexError: list index out of range'

I'm a beginner and this is my first receiving this message "IndexError: list index out of range," can someone please tell me how to fix it? and what exactly did I do wrong? Also if someone can run it and make sure it does what it's supposed to because I need another person other than me to run it(Professor's instruction)
This is the output it gave me -
Traceback (most recent call last):
File "", line 74, in
File "", line 24, in user
IndexError: list index out of range
Here's my code:
print ("Dish No. Dish Name Price ")
print (" -------- --------- ------")
print (" 1 Gang Gai $10.00")
print (" 2 Pad Thai $8.75")
print (" 3 Pad Cashew $9.50")
print (" 4 Pad Prik $10.25")
print (" 5 Peanut Curry $9.50")
print (" 6 Curry Noodles $11.25")
def user():
array = [10,8.75,9.50,10.25,9.50,11.25]
cart = []
while True:
x = int(input("Enter the item number you want (1-6):"))
check = checker(x)
if check == "wrong number":
print("Enter a valid number")
pass
cart.append(array[x-1])
xx=input("Would you like to order another item( Yes or No)?: ")
if xx.lower() == "no":
break
checkout(cart)
# if xx=='No'.lower():
# return array[x-1]
# else:
# return array[x-1]+user(array)
def seniorCitizen():
print("Are you 65 years or older(Yes or No)? ")
xsenior = input()
if xsenior.lower() == "yes":
senior = True
else:
senior = False
return senior
def checker(num):
if num > 6 or num < 1:
return "wrong number"
def checkout(cart):
senior = seniorCitizen()
titems = 0
for item in cart:
titems = titems + item
print(" Bill Information ")
print("-------------------------------")
print("Total of all items: $",titems)
if senior == True:
boomercount = titems * 0.1
boomercount = round(boomercount, 2)
print("Total senior discounts:-$", boomercount)
tax = round((titems-boomercount)*0.06, 2)
print("Taxes: $",tax)
print(" Bill: $", round(((titems-boomercount)+tax), 2))
else:
tax = round(titems*0.06, 2)
print("Taxes: $",tax)
print(" Bill: $", round((titems+tax), 2))
user()
while True:
x = int(input("Enter the item number you want (1-6):"))
check = checker(x)
if check == "wrong number":
print("Enter a valid number")
pass
cart.append(array[x-1])
The problem is the pass statement. It does not restart the loop -- it does nothing at all. So if the user enters a wrong number, it prints an error message but then it keeps going and tries to access array[x-1] which is out of range.
Use continue which will start the loop over, instead of pass.

Getting data type conversion error from user input

I am having an issue with this code, I have tried changing the data type of just about every part of it. I cant see where the error is. I am aware that this code has probably got a lot of issues. I am very new to programming.
team_1 = input(str("enter the name of team one "))
team_1_avg_goals = input(str("enter the average goals for " + team_1))
team_1_win_percentage = input(str("enter the win rate of " + team_1))
team_2 = input(str("enter the name of team two "))
team_2_avg_goals = input(str("enter the average goals for " + team_2))
team_2_win_percentage = input(str("enter the win percentage for " + team_2 ))
if team_1_win_percentage > team_2_win_percentage:
print(team_1 + " should win")
else: print(team_2 + " should win")
total_goals = team_2_avg_goals + team_1_avg_goals/2
print(float(total_goals))
Error:
TypeError: unsupported operand type(s) for /: 'str' and 'int'
You have to convert team_1_avg_goals to int. You can either do it on the input line:
team_1_avg_goals = int(input("enter the average goals for " + team_1))
team_2_avg_goals = int(input("enter the average goals for " + team_2))
or here:
total_goals = int(team_2_avg_goals) + int(team_1_avg_goals)/2

String argument error with dictionary commands

I am trying to create a basic online store in python. But whenever I try to 'buy' an item it shows an error with my dictionary or something I am not sure.
The error: users[n]["Transactions"] = users[n]["Transactions"] + str(names_f, "bought", quanti, "of", final[choice*3], "with a total price of $"+price)
TypeError: str() takes at most 3 arguments (6 given)
coun = 0
users = [{"name":"Jack","username":"ja", "cc":'12345',"email":'whwhwwhh', "code": '111', "Transactions": ""}]
def sign_in():
username = input("Enter username")
for i in range (len(users)):
for x in users[i].values():
if x == username:
pin = input("Enter pin")
if pin == users[i].get("code"):
print("Welcome", users[i].get("name"))
menu(username,users[i].get("name"))
break
else:
print("Wrong pin")
sign_in()
def menu (usern, names_f):
global coun
if coun == 0:
order = ''
total = 0
for i in range (len(categories)):
print(str(i+1)+".", categories[i])
choice = int(input("Choose a category by typing the number beside the categories name."))-1
print("Items in this list are")
print("Itemname \t Price \t Stock")
final = location[choice]
for c in range((int(len(final)/3))):
print(str(c+1)+'.',str(final[c*3]),"\t",'$'+str(final[c*3+1])), "\t", str(final[(c*3)+2])
choice = int(input("Which item (Type number on left of the item name)"))-1
while True:
quanti = int(input("How many do you want to buy"))
if quanti > final[choice*3+2]:
print("Sorry your request for", quanti, "Is more than we have at the store please try again")
continue
else:
price = str(quanti*final[choice*3+1])
final[choice*3+2] = final[choice*3+2]-quanti
print("Thank you for your purchasing",quanti,"of", final[choice*3], "Your total price of this buy is", '$'+price)
for n in range (len(users)):
if usern == users[n].get("username"):
users[n]["Transactions"] = users[n]["Transactions"] + str(names_f, "bought", quanti, "of", final[choice*3], "with a total price of $"+price)
order += str(quanti, 'of', final[choice*3])
price += int(price)
done = input("Do you want to check out then type '1' if you want to continue type '2'")
if done == '1':
print("Thank you")
print ("Invoice:", order, "/n total price (HKD) $"+str(price))
else:
coun += 1
menu(usern,names_f)
variable_name = users[n]["Transactions"] + str(names_f) + "bought" + str(quanti) + "of" + str(final[choice*3]) + "with a total price of $"+ str(price)
users[n]["Transactions"] = variable_name
You will maybe need to declare variable_name somewhere.
Problem is that str usage is following
str(object, encoding=encoding, errors=errors)
but whenever you pass comma it count it as another parameter.
P.S. I'm not sure if you need all those str in my solution.
str is a class, and as stated in the docs you can pass up to 3 parameters to it:
class str(object=b'', encoding='utf-8', errors='strict')
Also, it also says what it does:
Return a string version of object. If object is not provided, returns the empty string.
Meaning it is used to cast other types to string. Thus, you need to convert every int individually:
users[n]["Transactions"] = users[n]["Transactions"] + str(names_f) + " bought " + str(quanti) + " of " + str(final[choice*3]) + " with a total price of " + str(price)
Note the spaces before and after every string. Alternatively, you can format your string:
users[n]["Transactions"] = users[n]["Transactions"] + '%s bought %s of %s with a total price of %s' % (names_f, quanti, final[choice*3], price)
As a side note, it's worth checking what happens when the first transaction is made. If the key Transactions does not yet exist, you need to add an initial value before accessing it.
I usually do it like:
if key not in dict_:
dict_[key] = 'my initial value'
dict_[key] += 'add my stuff'
another solution would be using the get method, which allows you to add a default value:
dict_.get(key, 'default')
Note that this will not add the key to the dictionary, meaning that trying to access its value later on will still result in a Key Error.

Python type-error issue

I'm writing a simple program to help generate orders for a game I'm a member of. It falls into the catergory of programmes I don't actually need. But now I've started I want it to work. It all pretty much runs smoothly but I can't figure out how to stop a type-error ocurring about half way through. Here's the code;
status = 1
print "[b][u]magic[/u][/b]"
while status == 1:
print " "
print "would you like to:"
print " "
print "1) add another spell"
print "2) end"
print " "
choice = input("Choose your option: ")
print " "
if choice == 1:
name = raw_input("What is the spell called?")
level = raw_input("What level of the spell are you trying to research?")
print "What tier is the spell: "
print " "
print "1) low"
print "2) mid"
print "3) high"
print " "
tier = input("Choose your option: ")
if tier == 1:
materials = 1 + (level * 1)
rp = 10 + (level * 5)
elif tier == 2:
materials = 2 + (level * 1.5)
rp = 10 + (level * 15)
elif tier == 3:
materials = 5 + (level * 2)
rp = 60 + (level * 40)
print "research ", name, "to level ", level, "--- material cost = ",
materials, "and research point cost =", rp
elif choice == 2:
status = 0
Can anyone help?
edit
The error I get is;
Traceback (most recent call last):
File "C:\Users\Mike\Documents\python\magic orders", line 27, in <module>
materials = 1 + (level * 1)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
A stacktrace would've helped, but presumably the error is:
materials = 1 + (level * 1)
‘level’ is a string, and you can't do arithmetic on strings. Python is a dynamically-typed language, but not a weakly-typed one.
level= raw_input('blah')
try:
level= int(level)
except ValueError:
# user put something non-numeric in, tell them off
In other parts of the program you are using input(), which will evaluate the entered string as Python, so for “1” will give you the number 1.
But! This is super-dangerous — imagine what happens if the user types “os.remove(filename)” instead of a number. Unless the user is only you and you don't care, never use input(). It will be going away in Python 3.0 (raw_input's behaviour will be renamed input).
Here is an example of a Type Error and how to fix it:
# Type Error: can only concatenate str (not "int") to str
name = "John"
age = 30
message = "My name is " + name + " and I am " + age + " years old."
# Fix:
message = "My name is " + name + " and I am " + str(age) + " years old."
In the above example, the error message says that we're trying to concatenate a string and an integer which is not possible. So, we need to convert the integer to string using str() function to fix the error.

Categories

Resources