Using a dictionary, practice code - python

I apologize for my earlier questions as they were vague and difficult to answer. I am still fairly new to programming and am still learning the ins and outs of it all. So please bear with me. Now to the background information. I am using python 3.3.0. I have it loaded onto the Eclipse IDE and that is what I am using to write the code and test it in.
Now to the question: I am trying to learn how to create and use dictionaries. As such my assignment is to create a price matching code that through user interface will not only be able to search through a dictionary for the items (which are the keys and the locations and prices which are the values associated with the keys.) So far I have created a user interface that will run through well enough without any errors however (at least within the IDE) When I run through and input all of the prompts the empty dictionary is not updated and as such I cannot then make a call into the dictionary for the earlier input.
I have the code I have written so far below, and would like if someone could tell me if I am doing things correctly. And if there are any better ways of going about this. I am still learning so more detailed explanations around code jargon would be useful.
print("let's Price match")
decition = input("Are you adding to the price match list?")
if decition == "yes":
pricematchlist = {"Snapple":["Tops",99]}
location = input("Now tell me where you shopped")
item = input("Now what was the item")
price = input("Now how much was the item")
int(price)
pricematchlist[item]=location,price
print(pricematchlist)
else:
pricematchlist = {"Snapple":["Tops",99]}
reply = input("Ok so you want to search up a previous price?")
if reply == "yes":
search = input("What was the item?")
pricematchlist.item(search)

These are a few minor changes. For dictionaries: you are using them correctly.
print("let's Price match")
pricemathlist = {"Snapple":["Tops", 99]} # assign it here
decition = input("Are you adding to the price match list?").lower() #"Yes"-->"yes"
if decition == "yes":
# pricematchlist = {"Snapple":["Tops",99]}
# If this whole code block is called repeatedly, you don't want to reassign it
location = input("Now tell me where you shopped")
item = input("Now what was the item")
price = int(input("Now how much was the item"))
# int(price) does nothing with reassigning price
pricematchlist[item]=location,price
print(pricematchlist)
else:
reply = input("Ok so you want to search up a previous price?").lower()
if reply == "yes":
search = input("What was the item?")
print pricematchlist[search] # easier way of accessing a value

Related

Python: How to require an input to correspond with a previous input?

all. Python newbie here.
Simply-put here is my basic idea:
I want to create a "Login" feature where people must input a valid username from a preset tuple.
Next, once a valid name is entered, they will be asked to enter the corresponding code name, which is saved to a dictionary. (I have a feeling that I am over-complicating this, or maybe the dictionary is the wrong idea entirely, so any advice on how to simplify would be great).
real_names = ("JD", "JM" "JC")
player_ids = {"JD":"Arrow","JM":"Bullet","JC":"Blade"}
while True:
# user must input a name from the real_names tuple
name = input("User unidentified. Please input your name: ")
# if username is not in tuple, rerun script
if not name in real_names:
print("Invalid username detected")
continue
print(f"Positive ID! Welcome, {name}")
break
The above code works just fine. But next, I want to make a new input that requires the player ID to match the previously input name. In Pseudo-code, something like this:
# While True Loop:
id = input("Please confirm user Code Name: ")
#ID must correspond to keyword in dictionary
if ID value does not match username Keyword:
print("Invalid ID")
continue
print("Identity confirmed!")
break
Am I on the right path? If so, how would I syntax the second part? If the dictionary is the wrong idea entirely, please provide a good alternative. Many thanks!
player_ids[name] is the value you're looking for. So, you want something like this:
if id != player_ids[name]:
print("invalid ID")
Also, the dictionary already keeps track of player names, so you don't need the real_names tuple.
This previous answer works perfect, because you are looking up the value based on the key from a dictionary. Finally, one little tip, it's always good practice to avoid naming variables after reserved variables and keywords, that is to say, use another variable name just in case you are going to use to use the id() function again in the program.

why am i unable to use list object syntax and am met with AttributeError: when running my program

i apologise for the longevity of this question
I want to write a piece of code which essentially checks if the str name of an input has already been added within a txt file, let me tell you this scenario:
I am using Classes and Listing in order to structure my data (stored in a txt file) for comparisons later, I am using the code that follows:
import csv
class Volunteer:
def __init__(self,name,coin_type,weight_of_bag,true_count):
self.name = name
self.coin_type = coin_type #a function allowing me to class the data
self.weight_of_bag = weight_of_bag
self.TrueCount = true_count
with open("CoinCount.txt","r+") as csvfile: #opens file as CSV *IMPORTANT*
volunteers = []
for line in csvfile:
volunteers.append(Volunteer(*line.strip().split(',')))
I have also created some more simple code such as a menu etc, within this menu though I want to include the ability to input new volunteers, for now i havent actually gotten to the stage of appending new data to the txt file however, i am at the moment trying to create an inspection which checks if the inputted volunteers name has already been used before, just for more information, i will send the data within the txt file:
Abena,5p,325.00,Y
Malcolm,1p,3356.00,Y
Jane,£2,120.00,Y
Andy,£1,166.25,N
Sandip,50p,160.00,Y
Liz,20p,250.00,Y
Andy,20p,250.00,Y
Andy,50p,160.00,Y
Jane,£1,183.75,N
Liz,£,179.0,N
Liz,50p,170.0,N
Jane,50p,160.0,Y
Sandip,£1,183.0,N
Jane,£2,132.0,N
Abena,1p,3356.0,N
Andy,2p,250.0,N
Abena,£1,175.0,Y
Malcolm,50p,160.0,Y
Malcolm,£2,175.0,N
Malcolm,£1,175.0,Y
Malcolm,1p,356.0,Y
Liz,20p,250.0,Y
Jane,£2,120.0,Y
Jane,50p,160.0,Y
Andy,£1,175.0,Y
Abena,1p,359.56,N
Andy,5p,328.5,N
Andy,£2,108.0,N
Malcolm,£2,12.0,N
I will also give you the code for this part of the menu so that if you wish to explain to me how to fix it you will be able to use the same variable names
def open_menu_1():
inputvolunteername = input("Enter the volunteers name you wish to add: ")
if hasNumbers(inputvolunteername):
yes_or_no = input("volunteer name contains numbers, would you like to try again? ")
if yes_or_no == "yes" or "Yes":
print("")
open_menu_1()
else:
print("")
print("you have been sent back to the main menu")
print("")
open_menu()
elif any(not c.isalnum() for c in inputvolunteername):
yes_or_no = input("volunteer name contains special characters, would you like try again? ")
if yes_or_no == ("yes" or "Yes"):
open_menu_1()
else:
print("")
print("you have been sent back to the main menu")
print("")
elif inputvolunteername == volunteers[0].name:
print("oi")
I designed a tiny grain of the code i would need to test out if it would work,that is displayed at the bottom of the code above
i essentially ran the program and typed in as the input the first name on the txt file (Abena) and by doing so, the console printed "oi". I thought this would be as difficult as this part of the code got as i thought all i would have to do now is replace
elif inputvolunteername == volunteers[0].name:
print("oi")
with
elif inputvolunteername == volunteers[0:].name:
print("oi")
i thought this would work because in lists this usually would go through all from 0 to infinity until there was nothing else to search from that name class category, however in actuality once i ran the program i was greeted with the following message:
elif inputvolunteername == volunteers[0:].name:
AttributeError: 'list' object has no attribute 'name'
this confused me as I do have an attribute 'name' and that is made evident by the fact that that the other line of code which i tested out did work however by simply adding a colon it says that there is no attribute,
please let me know what i need to change to the bottom line of code in order to make the program detect whether the inputvolunteername is equal to any of the names already written on the txt file.
There are duplicates in CSV... so to test for name in volunteer list of names I recommend using set()
inputvolunteername in set([v.name for v in volunteers])
The following return True
'Abena' in set([v.name for v in volunteers])

Changing amount of questions based on what the user says in Python

I am trying to have a Python script that asks you how many URLs you want to input, then asks for that amount of URL. So if you say that you have 5 URLs, then it would ask you for a URL 5 times.
So it asks for URLs, you say you have X amount of URLs, so it asks for X amount of different URLs.
The only thing i can think of is the following.
while True:
if amount > 1:
url1 = input("Whats your first url? ")
continue
if amount > 2:
url2 = input("Whats your second url? ")
continue
Above is the only thing i can think of as, I'm relatively uninformed regarding coding and python as a language. If you have a better way of doing this, please let me know and tell me what libraries i need to either install or import, sorry if im asking alot but once again, i'm not the greatest at coding, Thanks in advance.
You could do something like this:
urlnum = int(input("How many urls?"))
urllist = []
for e in range(urlnum):
urllist.append(input("Type URL %s" % str(e+1)))
then to get a url, you would use urllist[0] to get the first one, urllist[1] to get the second, etc.

How can I work around a KeyError in Python? [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
I am trying to create a Forecasting tool, which analyses historical passenger traffic at a given airport. The anylysis will be based on a linear regression with various GDPs (Gross Domestic Product) of countries related to the airport.
A person can type in the name of the independant variable, which then gets selected from the Excel file.
Once a person gets the question "Which Country's GDP would you like to set as the independant variable for the Regression Analysis?", there is the possibility of typing a country wrong. In that case I receive a KeyError.
I am trying to work around that with "try / except", but I still receive a KeyError (See lines 36-49). I would really appreciate some help!
Thank you!
If it helps, here is the GitHub Link: https://github.com/DR7777/snowflake
(See lines 36-49 of main_file.py)
Here is my code:
Ive tried with while loops, for / except, but it seems I am too new to understand.
# This part saves the first row of the Excel as a list,
# so I can give the user a list of all the countries,
# if the person types in a country, that's not on the list.
loc = ("IMF_Country_GDP_Data.xlsx")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)
list_of_countries = sheet.row_values(0)
possible_selection = (list_of_countries[1:]) #This is the list with all the possible countries, without the Excel cell A1
#Introduction
print("Hello, welcome to the Air Traffic Forecasting Tool V0.1!")
print("Which Country's GDP would you like to set as the independant variable for the Regression Analysis?")
Country_GDP = input("Please type your answer here: ")
#here we check, if the typed Country is in the list
try:
possible_selection == Country_GDP
print("Your country is on the list.")
except KeyError:
print("Oh no! You typed a country, which is not in our database!")
print("Please select one of the countries listed below and try again")
print(possible_selection)
#now continuing with the previous code
print("Ok, I will conduct the analysis based on the GDP of " + str(Country_GDP) + "!")
print("Here are your results: ")
#here is the rest of the code
What I want to achieve is:
If a person types a name, which is on the list of countries, the program runs the regression.
If the country is not on the list, I dont want to receive a KeyError. I would like the program to say:
Oh no! You typed a country, which is not in our database!
Please select one of the countries listed below and try again
And then print the possible_selection variable, so the user can see which selection he has.
Thank you very much!
No need to get a key error at all. Just use in.
while True:
selection = input('Which country?')
if selection in list_of_countries:
print('Your country is on the list')
break
else:
print('You typed an invalid entry, lets try again')

Building a ranking list in Python: how to assign scores to contestants?

(I posted this on the wrong section of Stackexchange before, sorry)
I'm working on a assignment which is way above my head. I've tried for days on end figuring out how to do this, but I just can't get it right...
I have to make a ranking list in which I can enter a user, alter the users score, register if he/she payed and display all users in sequence of who has the most score.
The first part I got to work with CSV, I've put only the basic part in here to save space. The menu and import csv have been done: (I had to translate a lot from my native language, sorry if there is a mistake, I know it's a bad habit).
more = True
while more:
print("-" * 40)
firstname = raw_input("What is the first name of the user?: ")
with open("user.txt", "a") as scoreFile:
scoreWrite = csv.writer(scoreFile)
scoreWrite.writerow([firstname, "0", "no"])
scoreFile.close()
mr_dnr = raw_input("Need to enter more people? If so, enter 'yes' \n")
more = mr_dnr in "yes \n"
This way I can enter the name. Now I need a second part (other option in the menu of course) to:
let the user enter the name of the person
after that enter the (new) score of that person.
So it needs to alter the second value in any entry in the csv file ("0") to something the user enters without erasing the name already in the csv file.
Is this even possible? A kind user suggested using SQlite3, but this basic CSV stuff is already stretching it far over my capabilities...
Your friend is right that SQlite3 would be a much better approach to this. If this is stretching your knowledge too far, I suggest having a directory called users and having one file per user. Use JSON (or pickle) to write the user information and overwrite the entire file each time you need to update it.

Categories

Resources