Why won't my variables update their values? - python

I am using python to make a five guys nutrition calculator, and entered all the nutritional info into a dictionary. I have individual variables such as carbs, calories, protein, etc. and update them by adding the values inside them with the values from dictionaries. The dictionary is long, so the first couple keys are
fiveguys_menu = {'burger': {'hamburger':[700, 39, 39, 43, 19.5, 2, 430, 8, 2], 'cheeseburger':[770, 39, 43, 49, 23.5, 2.2, 790, 8, 2],...}
first_food = input("What're you tryna eat? Please state whether you want a burger or fries, fatty.\n").lower().replace(" ", "")
if 'burger' in first_food:
while True:
burger_type = input('Out of hamburger, cheeseburger, baconburger, and bacon cheeseburger, which one do you want?\n').lower().replace(" ", "")
if 'ham' in burger_type:
calories = fiveguys_menu['burger']['hamburger'][0]
carbs = fiveguys_menu['burger']['hamburger'][1]
protein = fiveguys_menu['burger']['hamburger'][2]
total_fat = fiveguys_menu['burger']['hamburger'][3]
sat_fat = fiveguys_menu['burger']['hamburger'][4]
trans_fat = fiveguys_menu['burger']['hamburger'][5]
sodium = fiveguys_menu['burger']['hamburger'][6]
sugar = fiveguys_menu['burger']['hamburger'][7]
fiber = fiveguys_menu['burger']['hamburger'][8]
print_message("One hamburger coming up.")
print(calories, carbs, protein, total_fat, sat_fat, trans_fat, sodium, sugar, fiber)
However, when trying to update the macro variables with the toppings list, the variables will not update.
fiveguys_toppings = {'a1sauce':[15, 3, 0, 0, 0,0, 280, 2, 0], 'barbeque':[60, 15, 0, 0, 0, 0, 400, 10, 0], ...}
while True:
burger_toppings = input("The toppings available are A1 Sauce, barbeque, green pepper, grilled mushrooms, hot sauce, jalapenos, ketchup, lettuce, mayo, mustard, onions, pickles, relish, and tomatoes\nWhat toppings do you want? Please be specific to the spelling listed. \n").lower().replace(" ", "")
if burger_toppings == True:
calories += fiveguys_toppings[burger_toppings][0]
carbs += fiveguys_toppings[burger_toppings][1]
protein += fiveguys_toppings[burger_toppings][2]
total_fat += fiveguys_toppings[burger_toppings][3]
sat_fat += fiveguys_toppings[burger_toppings][4]
trans_fat += fiveguys_toppings[burger_toppings][5]
sodium += fiveguys_toppings[burger_toppings][6]
sugar += fiveguys_toppings[burger_toppings][7]
fiber += fiveguys_toppings[burger_toppings][8]
print(calories, carbs, protein, total_fat, sat_fat, trans_fat, sodium, sugar, fiber)
Why does this while True loop not update the macro variables?

burger_toppings = input(...) - so it will equal whatever was input, not the boolean True. You can change your if statement to be if burger_toppings:, which will evaluate to True if burger_toppings is true-ish (not empty string, not empty list, not None object, etc).

Your code checks for burger_toppings to be True, which it never will be since it's a str. Try:
fiveguys_toppings = {
'a1sauce': [15, 3, 0, 0, 0, 0, 280, 2, 0],
'barbeque': [60, 15, 0, 0, 0, 0, 400, 10, 0], ...}
while True:
burger_toppings = input(
"The toppings available are A1 Sauce, barbeque, green pepper, "
"grilled mushrooms, hot sauce, jalapenos, ketchup, lettuce, mayo, "
"mustard, onions, pickles, relish, and tomatoes.\n"
"What toppings do you want? "
"Please be specific to the spelling listed.\n"
).lower().replace(" ", "")
if burger_toppings not in fiveguys_toppings:
print(f"{burger_toppings.capitalize()} is not one of the options!")
continue
calories += fiveguys_toppings[burger_toppings][0]
carbs += fiveguys_toppings[burger_toppings][1]
protein += fiveguys_toppings[burger_toppings][2]
total_fat += fiveguys_toppings[burger_toppings][3]
sat_fat += fiveguys_toppings[burger_toppings][4]
trans_fat += fiveguys_toppings[burger_toppings][5]
sodium += fiveguys_toppings[burger_toppings][6]
sugar += fiveguys_toppings[burger_toppings][7]
fiber += fiveguys_toppings[burger_toppings][8]
print(calories, carbs, protein, total_fat, sat_fat, trans_fat, sodium, sugar, fiber)

Related

How to compare an input string to A set of lists and project output as the most matching one? [python]

As a beginner I have a few doubts about this project I'm working on
The general idea of this project is to allow users to be able to detect a certain disease through symptoms
I want the program to match the input with the provided lists and pick out the best match and print output.
The problem here is that the list provided with symptoms of diseases shares few common symptoms with each other. So the program must evaluate the entire set of lists and print the best match
I tried something
import re
input1 = input("Enter Your Symptoms: ".lower())
x = re.split("\s", input1) #used to seprate the words in the string and create a list out of it
# Symptoms
cadsym = ['chest pain' , 'body pain' , 'falling sick' , 'feeling faint' , 'shortness of breath']
vhdsym = ['swollen ankles' , 'fanting' , 'shortness of breath']
hasym = ['racing heartbeat', 'slow heartbeat', 'chest pain' , 'anxiety', 'sweating']
mhasym = ['cold sweat', 'heartburn', 'sudden dizziness', 'discomfort in joints']
jsym = ['itching', 'abdominal pain', 'weight loss', 'yellow eyes' , 'yellow nails', 'vomiting']
cpsym = ['rashes on skin' , 'fever' , 'sore throat' , 'brown spots' , 'itching']
msym = ['fever', 'runny nose' , 'sneezing' , 'pink eye' , 'skin rash', 'diarrhoea']
dsym = ['Eye pain' , 'fever' , 'muscle pain' , 'nausea' , 'joint pain', 'rash on thigh']
masym = ['pain in muscle' , 'pain in abdomin' , 'Night sweat' , 'shivering', 'fast heart rate' , 'mental confusion']
tcsym = ['chest pain','Night sweats','shortness of breath','blood cough']
disym = ['increase thirst','frequent urination','hunger','blurred vision','slow healing']
pnsym = ['fever','chills','sharp pain in chest','clammy skin']
htsym = ['nose bleeds','dizziness','morning headaches','irregular heart rhythms','vision changes','buzzing in the ears']
emsym = ['lot of mucus','tight chest','whistle sound while breathing']
cysym = ['bluish colour in sikn',' lips','nail beds']
hysym = ['itchy','red and watery eyes','rod of mouth being itchy','runny or blocked nose']
ansym = ['unusual headache','memory loss','slurred speech','forgotten words','trouble in walking','trouble in moving arms','trouble in moving legs']
hcsym = ['anxiety','shortness of breath','headache','daytime sleep even after sleeping a lot at night','daytime sluggishness']
bcsym = ['sleeping difficulty','sore throat','chest pressure','shortness of breath','runny nose']
asym = ['wheezing','anxiety','early awakening','shortness of breath at night','cough','throat irritation']
if x in cadsym:
print("You Might Have Coronary Artery Disease")
elif x in vhdsym:
print("You Might Have Vulvar Heart Disease")
elif x in hasym:
print("You Might Have Heart Arrhythmia ")
elif x in mhasym:
print("You Might Have Minor Heart Attack")
elif x in jsym:
print("You Might Have Jaundice")
elif x in cpsym:
print("You Might Have Chickenpox")
elif x in msym:
print("You Might Have Measles")
elif x in dsym:
print("You Might Have Dengue")
elif x in masym:
print("You Might Have Malaria")
elif x in tcsym:
print("You Might Have Tuberculosis")
elif x in disym:
print("You Might Have Diabetes")
elif x in pnsym:
print("You Might Have Pneumonia")
elif x in htsym:
print("You Might Have Hypertension")
elif x in emsym:
print("You Might Have Emphysema")
elif x in cysym:
print("You Might Have Cyanosis")
elif x in hysym:
print("You Might Have Hay Fever")
elif x in ansym:
print("You Might Have Anoxia")
elif x in hcsym:
print("You Might Have Hypercapnia")
elif x in bcsym:
print("You Might Have Bronchitis")
elif x in asym:
print("You Might Have Asthama")
else:
print("Not Registered")
As the response for each case is the same sentence with just the disease name changing, why not use a dict where the key is the disease name and the value is the list of symptoms.
A bigger challenge here might be that many of the symptoms include spaces, so any split of the full input string is going to prevent you from finding matches. For example, if the user enters shortness of breath, then x is going to contain ['shortness', 'of', 'breath']
There are two possible work arounds for this:
Ask the user to input one symptom at a time and put all of the symptoms into a list
Split of the symptom lists to all be single words only, but that's going to get a lot more false positives.
Here's my solution using sets, prompting the user for separate symptoms, and putting all of the disease data into a single constant dictionary.
# Use a set for user symptoms to prevent duplicates, and so we can compare
# against our database easily later.
user_symptoms = set()
print("Enter your symptoms one at a time. Leave the entry blank to stop.")
while True:
# .lower() needs to be OUTSIDE the input() call,
# otherwise it changes the prompt, not the input
x = input("Enter a symptom: ").lower()
if len(x):
user_symptoms.add(x)
else:
break
# Dict of diseases with symptoms as sets.
# We can use sets instead of lists as ordering is not important.
DIAGNOSES = {
"coronary artery disease": {'chest pain', 'body pain', 'falling sick', 'feeling faint', 'shortness of breath'},
"vulvar heart disease": {'swollen ankles', 'fanting', 'shortness of breath'},
"heart arrhythmia": {'racing heartbeat', 'slow heartbeat', 'chest pain', 'anxiety', 'sweating'},
"minor heart attack": {'cold sweat' 'heartburn', 'sudden dizziness', 'discomfort in joints'},
"jaundice": {'itching', 'abdominal pain', 'weight loss', 'yellow eyes', 'yellow nails', 'vomiting'},
"chickenpox": {'rashes on skin', 'fever', 'sore throat', 'brown spots', 'itching'},
"measles": {'fever', 'runny nose', 'sneezing', 'pink eye', 'skin rash', 'diarrhoea'},
"dengue": {'Eye pain', 'fever', 'muscle pain', 'nausea', 'joint pain', 'rash on thigh'},
"malaria": {'pain in muscle', 'pain in abdomin', 'Night sweat', 'shivering', 'fast heart rate', 'mental confusion'},
"tuberculosis": {'chest pain', 'Night sweats', 'shortness of breath', 'blood cough'},
"diabetes": {'increase thirst', 'frequent urination', 'hunger', 'blurred vision', 'slow healing'},
"pneumonia": {'fever', 'chills', 'sharp pain in chest', 'clammy skin'},
"hypertension": {'nose bleeds', 'dizziness', 'morning headaches', 'irregular heart rhythms', 'vision changes', 'buzzing in the ears'},
"emphysema": {'lot of mucus', 'tight chest', 'whistle sound while breathing'},
"cyanosis": {'bluish colour in sikn', ' lips', 'nail beds'},
"hay fever": {'itchy', 'red and watery eyes', 'rod of mouth being itchy', 'runny or blocked nose'},
"anoxia": {'unusual headache', 'memory loss', 'slurred speech', 'forgotten words', 'trouble in walking', 'trouble in moving arms', 'trouble in moving legs'},
"hypercapnia": {'anxiety', 'shortness of breath', 'headache', 'daytime sleep even after sleeping a lot at night', 'daytime sluggishness'},
"bronchitis": {'sleeping difficulty', 'sore throat', 'chest pressure', 'shortness of breath', 'runny nose'},
"asthma": {'wheezing', 'anxiety', 'early awakening', 'shortness of breath at night', 'cough', 'throat irritation'},
}
# Find any possible matches using set.intersection(). Put matches in a list.
matches = []
for dx, dx_symptoms in DIAGNOSES.items():
if user_symptoms.intersection(dx_symptoms):
matches.append(dx)
# Now print all the possible matches.
for match in matches:
print(f"You might have {match}.")
else:
print("No matching symptoms registered.")
Example run:
Enter your symptoms one at a time. Leave the entry blank to stop.
Enter a symptom: chest PAIN
Enter a symptom: anxiety
Enter a symptom: hunger
Enter a symptom: SORE throat
Enter a symptom:
You might have coronary artery disease.
You might have heart arrhythmia.
You might have chickenpox.
You might have tuberculosis.
You might have diabetes.
You might have hypercapnia.
You might have bronchitis.
You might have asthma.

I want to print out an itemized receipt with total cost

I am a beginner in programming and I'm working on the projects in Automate the Boring Stuff with Python, In the book there is a project to create a sandwich, then return the total cost. I want to add to my program by providing an itemized receipt. For example, if I put in an order for 1 sandwich with wheat and chicken and 3 sandwiches with white and turkey, the receipt should show something like this (I will format it better when I figure it out):
1 sandwich ---3.5
wheat, chicken
3 sandwich ---10.5.
white, turkey
Total --- 14.00
My challenge is storing the different sandwich orders into different variables and printing them out at the end.
My code below:
menu = {
'wheat': 1.5, 'white': 1, 'sourdough': 2,
'chicken': 2, 'turkey': 2.5, 'ham': 2, 'tofu': 3,
'cheddar': 0.5, 'mozzarella': 0.25, 'american': 0.5,
'mayo': 0.25, 'mustard': 0.25, 'lettuce': 0.5, 'tomato': 0.5
}
total = 0.0
subtotal = 0.0
while True:
order = {}
print('What bread would you like?')
order['bread'] = pyip.inputChoice(['wheat', 'white', 'sourdough'])
print('How about for your protein?')
order['protein'] = pyip.inputChoice(['chicken', 'turkey', 'ham', 'tofu'])
wantCheese = pyip.inputYesNo('Would you like cheese on the sandwich?')
if wantCheese == 'yes':
order['cheese'] = pyip.inputChoice(['cheddar', 'mozzarella', 'american'])
wantToppings = pyip.inputYesNo('Would you like to add extra toppings?')
if wantToppings == 'yes':
while True:
order['side'] = pyip.inputChoice(['mayo', 'mustard', 'lettuce', 'tomato'])
anotherTopping = pyip.inputYesNo('Would you like another topping?')
if anotherTopping == 'no':
break
orderNumber = pyip.inputInt('How many of those sandwiches would you like? ', min = 1)
for choice in order:
if order[choice] in menu.keys():
subtotal += menu[order[choice]]
total *= orderNumber
total += subtotal
subtotal = 0
anotherOrder = pyip.inputYesNo('Would you like to order another sandwich?')
if anotherOrder == 'no':
break
print(total)
Adjust the following as you see fit. FYI, while coding this up I had "let's get this to work" in mind as opposed to "let's make this as efficient as possible". Moreover, you should format the receipt however you like.
Importantly, I created a list called orders just before the while that will be used to store orders. The form of the elements of orders will be 3-tuples where the first element of the 3-tuple records orderNumber, the third element records the subtotal, and the second element is an order dictionary, just as in your original code, except order["side"] will be a list as this allows for multiple additional toppings to be added. For the sample output below, orders is
[(2, {'bread': 'wheat', 'protein': 'chicken', 'cheese': 'cheddar', 'side': ['mustard', 'lettuce']}, 9.5), (1, {'bread': 'sourdough', 'protein': 'turkey', 'side': []}, 4.5)]
As you can see, there are 2 orders of 'wheat', 'chicken', 'cheddar', 'mustard', 'lettuce' (subtotal 9.5) and 1 order of 'sourdough', 'turkey' (subtotal 4.5).
I hope this helps. Any questions please let me know.
import pyinputplus as pyip
menu = {'wheat': 1.5, 'white': 1, 'sourdough': 2,
'chicken': 2, 'turkey': 2.5, 'ham': 2, 'tofu': 3,
'cheddar': 0.5, 'mozzarella': 0.25, 'american': 0.5,
'mayo': 0.25, 'mustard': 0.25, 'lettuce': 0.5, 'tomato': 0.5
}
orders = []
while True:
order = {}
# choose bread
print("What bread would you like?")
order['bread'] = pyip.inputChoice(['wheat', 'white', 'sourdough'])
# choose protein
print("How about for your protein?")
order['protein'] = pyip.inputChoice(['chicken', 'turkey', 'ham', 'tofu'])
# choose cheese
wantCheese = pyip.inputYesNo("Would you like cheese on the sandwich?")
if wantCheese == 'yes':
order['cheese'] = pyip.inputChoice(['cheddar', 'mozzarella', 'american'])
# choose extra toppings
order["side"] = []
wantToppings = pyip.inputYesNo("Would you like to add extra toppings?")
if wantToppings == 'yes':
while True:
order["side"].append(pyip.inputChoice(
['mayo', 'mustard', 'lettuce', 'tomato']))
anotherTopping = pyip.inputYesNo("Would you like another topping?")
if anotherTopping == 'no':
break
# order number
orderNumber = pyip.inputInt(
"How many of those sandwiches would you like?", min = 1)
# subtotal
subtotal = sum(menu[order[key]] for key in order if key != 'side')
subtotal += sum(menu[j] for j in order['side'])
subtotal *= orderNumber
# add 3-tuple to orders list
orders.append((orderNumber, order, subtotal))
# another order?
anotherOrder = pyip.inputYesNo("Would you like to order another sandwich?")
if anotherOrder == 'no':
break
# add subtotals to form total
total = sum(order[2] for order in orders)
# print orders (for programmer use)
print(f"\nOrders: {orders}")
# print receipt
print(f"\nReceipt\n")
for order in orders:
print(f"{order[0]} sandwich ---{order[2]}")
print(" ", end = "")
for key in order[1]:
if isinstance(order[1][key], list):
for x in order[1][key]:
print(x, end = ", ")
else:
print(order[1][key], end = ", ")
print("\n")
print(f"Total --- {total}")
Sample output:
Receipt
2 sandwich ---9.5
wheat, chicken, cheddar, mustard, lettuce,
1 sandwich ---4.5
sourdough, turkey,
Total --- 14.0

How do I perform a search on a text file from a users input

The question I am trying to answer is
Query if a book title is available and present option of (a) increasing stock level or (b) decreasing the stock level, due to a sale. If the stock level is decreased to zero indicate to the user that the book is currently out of stock.
This is the text file
#Listing showing sample book details
#AUTHOR, TITLE, FORMAT, PUBLISHER, COST?, STOCK, GENRE
P.G. Wodehouse, Right Ho Jeeves, hb, Penguin, 10.99, 5, fiction
A. Pais, Subtle is the Lord, pb, OUP, 12.99, 2, biography
A. Calaprice, The Quotable Einstein, pb, PUP, 7.99, 6, science
M. Faraday, The Chemical History of a Candle, pb, Cherokee, 5.99, 1, science
C. Smith, Energy and Empire, hb, CUP, 60, 1, science
J. Herschel, Popular Lectures, hb, CUP, 25, 1, science
C.S. Lewis, The Screwtape Letters, pb, Fount, 6.99, 16, religion
J.R.R. Tolkein, The Hobbit, pb, Harper Collins, 7.99, 12, fiction
C.S. Lewis, The Four Loves, pb, Fount, 6.99, 7, religion
E. Heisenberg, Inner Exile, hb, Birkhauser, 24.95, 1, biography
G.G. Stokes, Natural Theology, hb, Black, 30, 1, religion
And this is the code i have so far
def Task5():
again = 'y'
while again == 'y':
desc = input('Enter the title of the book you would like to search for: ')
for bookrecord in book_list:
if desc in book_list:
print('Book found')
else:
print('Book not found')
break
again = input('\nWould you like to search again(press y for yes)').lower()
i already have a function which reads from the text file:
book_list = []
def readbook():
infile = open('book_data_file.txt')
for row in infile:
start = 0 # used to start at the beginning of each line
string_builder = []
if not(row.startswith('#')):
for index in range(len(row)):
if row[index] ==',' or index ==len(row)-1:
string_builder.append(row[start:index])
start = index+1
book_list.append(string_builder)
infile.close()
Any one have an idea on how i complete this task? :)
Get the titles from the book_list variable.
titles = [data[1].strip() for data in book_list]
Remove any white-space from the desc variable.
desc = desc.strip()
For instance If I'm searching for Popular Lectures book, but If I type Popular Lectures then I couldn't find it in the book_list Therefore you should remove the white characters from the input.
If the book is avail, then get the book name and stock value from the book_list
info = [(title, int(book_list[idx][5].strip())) for idx, title in enumerate(titles) if desc in title][0]
bk_nm, stock = info
Print the current situation
if stock == 0:
print("{} is currently not avail".format(bk_nm))
else:
print("{} is avail w/ stock {}".format(bk_nm, stock))
Example:
Enter the title of the book you would like to search for: Popular Lectures
Popular Lectures is avail w/ stock 1
Would you like to search again(press y for yes)y
Enter the title of the book you would like to search for: Chemical
The Chemical History of a Candle is avail w/ stock 1
Would you like to search again(press y for yes)n
Code:
book_list = []
def task5():
titles = [data[1].strip() for data in book_list]
again = 'y'
while again == 'y':
desc = input('Enter the title of the book you would like to search for: ')
desc = desc.strip() # Remove any white space
stock = [int(book_list[idx][5].strip()) for idx, title in enumerate(titles) if desc in title][0]
if stock == 0:
print("{} is currently not avail".format(desc))
else:
print("{} is avail w/ stock {}".format(desc, stock))
again = input('\nWould you like to search again(press y for yes)').lower()
def read_txt():
infile = open('book_data_file.txt')
for row in infile:
start = 0 # used to start at the beginning of each line
string_builder = []
if not (row.startswith('#')):
for index in range(len(row)):
if row[index] == ',' or index == len(row) - 1:
string_builder.append(row[start:index])
start = index + 1
book_list.append(string_builder)
infile.close()
if __name__ == '__main__':
read_txt()
task5()

How to find what number argument was chosen with the input statement?

The variable or the types and the costs:
pasta_types = "Lasagne, Spaghetti, Macaroni, Cannelloni, Ravioli, Penne, Tortellini, Linguine, Farfalle, Fusilli"
pasta_costs = "6.00, 4.00, 3.15, 8.50, 9.00, 3.15, 5.00, 4.00, 4.25, 4.75"
The function to see if the in put has a type of pasta that is in the varaible:
def inventory(pt):
return(pt.title() in pasta_types)
Input:
type = input('What pasta would you like: Lasagne, Spaghetti, Macaroni, Cannelloni, Ravioli, Penne, Tortellini, Linguine, Farfalle, and Fusilli ')
Calling Function:
have = inventory(type)
How do I find out what number of the argument that was chosen?
Here's an example of doing something like that which builds and uses a dictionary that associates the name of each pasta type with its cost:
pasta_types = "Lasagne, Spaghetti, Macaroni, Cannelloni, Ravioli, Penne, Tortellini, " \
"Linguine, Farfalle, Fusilli"
pasta_costs = "6.00, 4.00, 3.15, 8.50, 9.00, 3.15, 5.00, 4.00, 4.25, 4.75"
# Create a dictionary associating (lowercase) pasta name to its (float) cost.
inventory = dict(zip(pasta_types.lower().replace(' ', '').split(','),
map(float, pasta_costs.replace(' ', '').split(','))))
## Display contents of dictionary created.
#from pprint import pprint
#print('inventory dictionary:')
#pprint(inventory)
while True:
pasta_type = input('What pasta would you like: ' + pasta_types + '?: ')
if pasta_type.lower() in inventory:
break # Got a valid response.
else:
print('Sorry, no {!r} in inventory, please try again\n'.format(pasta_type))
continue # Restart loop.
print('{} costs {:.2f}'.format(pasta_type, inventory[pasta_type]))

Combining list entries into a dictionary

I am trying to get the first_name and last_name to combine together into a new dictionary entry. How many depends on how many people buy in the shop. If I buy 50 troops I always receive less than that.
import random, math
first_name = [ "Emily", "Steve" , "Dave" , "Bob" , "James" , "Jim" , "Jenny" , "Will" , "Ryan" ]
last_name = [ "Wright" , "Kalman" , "Meitzen" , "Cole" , "Robins" , "Harrison" , "Saturn" ]
troops = {}
money = 1000
def shop():
loop = 0
global money, first_name, last_name, troops
while loop == 0 :
print("""
Your Money = {}
(Number , Item , cost)
0, Quit ,N/A
1, Troop, 10
""".format(money))
shopq = int( input("What do you want to buy"))
if shopq == 1:
shopq2 = int( input("How many"))
if shopq2 > money :
print(" You cannot by this many")
else:
print("You can buy that many")
money = money - shopq2
troop_number = 0
while troop_number < shopq2 :
s_name = random.choice(first_name) + " " + random.choice(last_name)
troops[s_name] = 100
troop_number = troop_number + 1
print(troops)
print(" Money = {}".format(money))
elif shopq == 0:
break
class dropship:
def create(self, troops):
troop_number = 0
for k in troops :
troop_number = troop_number + 1
print("troops = {}".format(troop_number))
shop()
x = dropship()
x.create(troops)
Output:
Your Money = 1000
(Number , Item , cost)
0, Quit ,N/A
1, Troop, 10
What do you want to buy1
How many50
You can buy that many
{'Ryan Wright': 100, 'Bob Cole': 100, 'Bob Kalman': 100, 'Will Wright': 100, 'Dave Cole': 100, 'Dave Robins': 100, 'Emily Kalman': 100, 'Jenny Kalman': 100, 'Bob Harrison': 100, 'Emily Wright': 100, 'Will Cole': 100, 'Jim Wright': 100, 'Dave Kalman': 100, 'Dave Wright': 100, 'Bob Meitzen': 100, 'Jenny Wright': 100, 'Jenny Harrison': 100, 'Dave Saturn': 100, 'James Robins': 100, 'Bob Robins': 100, 'Dave Meitzen': 100, 'Steve Wright': 100, 'Bob Wright': 100, 'Steve Kalman': 100, 'Ryan Harrison': 100, 'Jim Saturn': 100, 'Steve Robins': 100, 'Ryan Cole': 100, 'Jim Meitzen': 100, 'James Cole': 100, 'Emily Cole': 100, 'Ryan Saturn': 100, 'Steve Harrison': 100}
Money = 950
Your Money = 950
(Number , Item , cost)
0, Quit ,N/A
1, Troop, 10
What do you want to buy0
troops = 33
You are creating random names and some of them will be the same, by chance, so they replace the previous entries in the dictionary (dictionary keys are unique). You'll have to change the way you do that. For instance:
import random
import itertools
random.sample(list(itertools.product(first_name, last_name)), 50)
But you should also get much larger pools of first and last names, otherwise you can only have 63 different full names.
The problem with your dictionary is that dictionary keys must be unique. Since you are using randomly chosen names spliced together as keys, it is very likely that you will generate 'Ryan Wright' (for example) more than once.
Here is what your code is doing that is causing you to come up with a "short" count:
troops['Ryan Wright'] = 100
troops['Bob Cole'] = 100
troops['Ryan Wright'] = 100
The third assignment used the same slot in the dictionary troops because the key is the same. If your code was just those three lines you'd have a dictionary with two entries in it, not the three that you'd hope for. You can see this happen in your code by adding the assert statement:
s_name = random.choice(first_name) + " " + random.choice(last_name)
assert s_name not in troops
troops[s_name] = 100
It won't fix your problem, but it will show you that your keys are colliding.

Categories