In your final line to compute cost:
subtotal=(askSize + askBeverage + askFlav)
You do not sum the variables you defined at the top of your file (with costs), but you concatenate the strings that the user typed instead. For instance askSize can be the string "small". So, what you do here could be written as:
subtotal=("small" + "tee" + "lemon")
In Python, using + between strings will concatenate them. It means it will add the strings one after another to make a larger one. Example: "foo" + "bar" = "foobar".
If you want to refer to the cost of each option, one solution (but there are other ones) would be to use a dictionary to store costs instead of several variables as you did:
# Dictionary of costs
costs = {"tea": 1.50,
"coffee": 1.50,
"small": 0,
"medium": 0.75,
"large": 1.75,
"mint": 0.50,
"lemon": 0.25,
"chocolate": 0.75,
"vanilla": 0.25,
"none": 0
}
Then, to get the number corresponding to a string, you get items from the dictionary:
tea_cost = costs["tea"] # tea_cost will be equal to 1.50
ask_size_cost = costs[askSize] # ask_size_cost will be equal to the cost of the asked size
Now, it is easy to get your total cost:
total_cost = costs[askSize] + costs[askBeverage] + costs[askFlav]
Of course, take care of string cases, everything must be lowercase in my example.
Hope it helps !
NB: You can do many improvements to the rest of your code, do not hesitate to read some Python code on the internet to get it better.
Answer from RomainTT on Stack OverflowIn your final line to compute cost:
subtotal=(askSize + askBeverage + askFlav)
You do not sum the variables you defined at the top of your file (with costs), but you concatenate the strings that the user typed instead. For instance askSize can be the string "small". So, what you do here could be written as:
subtotal=("small" + "tee" + "lemon")
In Python, using + between strings will concatenate them. It means it will add the strings one after another to make a larger one. Example: "foo" + "bar" = "foobar".
If you want to refer to the cost of each option, one solution (but there are other ones) would be to use a dictionary to store costs instead of several variables as you did:
# Dictionary of costs
costs = {"tea": 1.50,
"coffee": 1.50,
"small": 0,
"medium": 0.75,
"large": 1.75,
"mint": 0.50,
"lemon": 0.25,
"chocolate": 0.75,
"vanilla": 0.25,
"none": 0
}
Then, to get the number corresponding to a string, you get items from the dictionary:
tea_cost = costs["tea"] # tea_cost will be equal to 1.50
ask_size_cost = costs[askSize] # ask_size_cost will be equal to the cost of the asked size
Now, it is easy to get your total cost:
total_cost = costs[askSize] + costs[askBeverage] + costs[askFlav]
Of course, take care of string cases, everything must be lowercase in my example.
Hope it helps !
NB: You can do many improvements to the rest of your code, do not hesitate to read some Python code on the internet to get it better.
You need a subtotal variable you never declared, and then after every option selection you want to += increment it:
subtotal = 0
askName = str(input("What is your name?")).title()
askBeverage = str(input("What type of beverage would you like?")).title()
if askBeverage.lower() in ("t", "tea"): #ensures any variation of upper/lowercase will work
subtotal += 1.50
askSize = str(input("Would you like a small, medium, or large Tea?")).title() # SIZE
if askSize.lower() in ("small", "s"):
subtotal += 0
elif askSize.lower() in ('medium', 'm'):
subtotal += .75
elif askSize.lower() in ('large', 'l'):
subtotal += 1.75
else:
print("Invalid size specified.")
sys.exit()
askFlav =str(input("Any flavourings for your Tea? Your options are mint, lemon, or none")).title() # FLAVOURING
if askFlav.lower() in ("m", "mint"):
subtotal += .50
elif askFlav.lower() in ("l", "lemon"):
subtotal += .25
elif askFlav.lower() in ('none', 'n'):
subtotal += 0
else:
print("Invalid flavour specified.")
sys.exit()
python - Assign string elements to variables - Stack Overflow
How do I assign the value of a string to the name of an object?
How do I add a variable into a string in Python 3.8?
python - How to assign a value to a string? - Stack Overflow
Videos
Hello, I am learning classes. I have multiple instances of Drinks and I want to call a method of a certain object if the value of an input string is the same as the name of the object. For example I want to call the method show_price() on the object latte if the return value of the user input is "latte". I made it work with ifs but I don't want to do it for a huge number of instances. Is there anything I can do to automate this?
I tried request.show_price() , {request}.show_price() and f"{request}".show_price(). I got AttributeError: 'str' object has no attribute 'show_price'
request = input("What would you like? ")
if request == "latte":
latte.show_price()i use spyder if thats helpful
I would suggest a recursive traversion of the tree:
a=[('bp', 46), ('sugar', 98), ('fruc', 56), ('mom',65)]
d = dict(a)
tree= [
[
'a',
'bp',
[78, 25, 453, 85, 96]
],
[
['hi', ['no', ['ho', 'sugar', 3]], ['not', 'he', 20]],
[['$', 'fruc', 7185], 'might', 'old'],
'bye'
],
[
['not', ['<', 'mom', 385]],
[
['in', 'Age', 78.5],
[['not', ['and', 'bp', 206]], 'life', [['or', ['not', ['\\', 'bp', 5]], ['p', 'sugar', 10]], 'ordag',[['perhaps', ['deal', 'mom', 79]],
'helloo',[['or', ['pl', 'mom', 25]], 'come', 'go']]]],
'noway'
],
[['<', 'bp', 45], 'falseans', 'bye']
]
]
def replace(node):
if isinstance(node, str):
return d.get(node, node)
elif isinstance(node, list):
return [replace(el) for el in node]
else:
return node
replace(tree)
Quick hack, works in simple cases.
(note: you have an incorrect string here: '\' should be '\\')
- convert the structure to string
- perform the replacement using single quotes as a delimiter so it's safe against word inclusions in other bigger words
- parse back the string with replacements using
ast.literal_evalwhich does the heavy lifting (parsing back the valid literal structure text to a valid python structure)
code:
tree= [['a', 'bp', [78, 25, 453, 85, 96]],
[['hi', ['no', ['ho', 'sugar', 3]], ['not', 'he', 20]],
[['$', 'fruc', 7185], 'might', 'old'],
'bye'],[['not', ['<', 'mom', 385]],
[['in', 'Age', 78.5],[['not', ['and', 'bp', 206]],
'life',[['or', ['not', ['\\', 'bp', 5]], ['p', 'sugar', 10]],
'ordag',[['perhaps', ['deal', 'mom', 79]],
'helloo',[['or', ['pl', 'mom', 25]], 'come', 'go']]]],
'noway'],[['<', 'bp', 45], 'falseans', 'bye']]]
a=[('bp', 46), ('sugar', 98), ('fruc', 56), ('mom',65)]
str_tree = str(tree)
for before,after in a:
str_tree = str_tree.replace("'{}'".format(before),str(after))
new_tree = ast.literal_eval(str_tree)
print(type(new_tree),new_tree)
result:
<class 'list'> [['a', 46, [78, 25, 453, 85, 96]], [['hi', ['no', ['ho', 98, 3]], ['not', 'he', 20]], [['$', 56, 7185], 'might', 'old'], 'bye'], [['not', ['<', 65, 385]], [['in', 'Age', 78.5], [['not', ['and', 46, 206]], 'life', [['or', ['not', ['\\', 46, 5]], ['p', 98, 10]], 'ordag', [['perhaps', ['deal', 65, 79]], 'helloo', [['or', ['pl', 65, 25]], 'come', 'go']]]], 'noway'], [['<', 46, 45], 'falseans', 'bye']]]
So it's a hack but it's able to process data containing sets, lists, dictionaries, tuples, without too much hassle.
Strings are immutable. That means you can't assign to them at all. You could use formatting:
>>> s = 'abc{0}efg'.format('d')
>>> s
'abcdefg'
Or concatenation:
>>> s = 'abc' + 'd' + 'efg'
>>> s
'abcdefg'
Or replacement (thanks Odomontois for reminding me):
>>> s = 'abc0efg'
>>> s.replace('0', 'd')
'abcdefg'
But keep in mind that all of these methods create copies of the string, rather than modifying it in-place. If you want in-place modification, you could use a bytearray -- though that will only work for plain ascii strings, as alexis points out.
>>> b = bytearray('abc0efg')
>>> b[3] = 'd'
>>> b
bytearray(b'abcdefg')
Or you could create a list of characters and manipulate that. This is probably the most efficient and correct way to do frequent, large-scale string manipulation:
>>> l = list('abc0efg')
>>> l[3] = 'd'
>>> l
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> ''.join(l)
'abcdefg'
And consider the re module for more complex operations.
String formatting and list manipulation are the two methods that are most likely to be correct and efficient IMO -- string formatting when only a few insertions are required, and list manipulation when you need to frequently update your string.
Since strings are "immutable", you get the effect of editing by constructing a modified version of the string and assigning it over the old value. If you want to replace or insert to a specific position in the string, the most array-like syntax is to use slices:
s = "ABCDEFGH"
s = s[:3] + 'd' + s[4:] # Change D to d at position 3
It's more likely that you want to replace a particular character or string with another. Do that with re, again collecting the result rather than modifying in place:
import re
s = "ABCDEFGH"
s = re.sub("DE", "--", s)