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')
Related
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 1 year ago.
Improve this question
I found a problem which I cannot solve on my own and when I did my research - answers are not unanimous.
Consider the following python code:
rooms = {1: 'Foyer', 2: 'Conference Room'}
room = input('Enter the room number: ')
if not room in rooms:
print('Room does not exist.')
else:
print("The room name is " + rooms[room])
The program fails to find the rooms, but when we convert room variable into int (like below) program works fine.
rooms = {1: 'Foyer', 2: 'Conference Room'}
room = int(input('Enter the room number: '))
if not room in rooms:
print('Room does not exist.')
else:
print("The room name is " + rooms[room])
A lot of people says the problem is invalid syntax, but in my opinion it's more like mistmatched data type. I don't get any errors in that code. My question is why do most people think this is invalid syntax. What do you think?
You're correct and the ones who told you it was a syntax error, it isn't. It is exactly the "mismatched data type" since the keys on the variable "rooms" are integers, but the user input or the variable "room" is specifically not an integer or a number. In other words, the user input returns a string and the "rooms" variable keys are integers which create a mismatched data type when matched together by an if statement and can probably cause confusion. To prevent this, make sure to see if both values that you're gonna be comparing are the same data types.
I agree with wondercricket...no error handling. rather than converting to int in the original input, if you move it further down, you could use it to handle the usecase of a string (invalid) input...
rooms = {1: 'Foyer', 2: 'Conference Room'}
room = input('Enter the room number: ')
try:
if int(room) in rooms:
print("The room name is " + rooms[int(room)])
else:
print("could not find a room based on the number you entered...please try again")
except:
print('Please enter the room number as a number')
(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.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I’m teaching myself programming, using Python as my initial weapon of choice.
I have learnt a few basics and decided to set myself the challenge of asking the user for a list of names, adding the names to a list and then finally writing the names to a .csv file.
Below is my code. It works.
My question is what would you do differently, i.e. how could this code be improved for readability and efficiency. Would you approach the situation differently, structure it differently, call different functions? I am interested in, and would appreciate a great deal, the feedback from more experienced programmers.
In particular, I find certain parts clunky; such as having to specify to the user the required format for data entry. If I were to simply request the data (name age location) without the commas however, then each record, when written to .csv, would simply end up as one record per cell (Excel) – this is not the desired result.
#Requesting user input.
guestNames = input("Please enter the names of your guests, one at a time.\n"\
"Once you have finished entering the information, please type the word \"Done\".\n"\
"Please enter your names in the following format (Name, Age, Location). ").capitalize()
guestList.append(guestNames)
while guestNames.lower() != "done".lower() :
guestNames = input("Please enter the name of your " + guestNumber[number] + " guest: ").capitalize()
guestList.append(guestNames)
number += 1
#Sorting the list.
guestList.sort()
guestList.remove("Done")
#Creating .csv file.
guestFile = open("guestList.csv","w")
guestFile.close()
#Writing to file.
for entries in guestList :
guestFile = open("guestList.csv","a")
guestFile.write(entries)
guestFile.write("\n")
guestFile.close()
I try to write down your demands:
Parse the input string according to its structure (whatever) and save results into a list
Format the result into CSV-format string
write the string to a CSV file
First of all, I would highly recommend you to read the a Python string operation and formatting tutorial like Google Developer Tutorial. When you understand the basic operation, have a look at official documentation to see available string processing methods in Python.
Your logic to write the code is right, but there are two meaningless lines:
while guestNames.lower() != "done".lower()
It's not necessary to lower "done" since it is already lower-case.
for entries in guestList :
guestFile = open("guestList.csv","a")
Here you open and close the questList.csv every loop, which is useless and costly. You could open the file at the beginning, then save all lines with a for loop, and close it at the end.
This is a sample using the same logic and different input format:
print('some notification at the beginning')
while true:
guestNames = input("Please enter the name of your " + guestNumber[number] + " guest: ").capitalize()
if guestNames == 'Done':
# Jump out of the loop if user says done
break
else:
# Assume user input 'name age location', replace all space with commas
guestList.append(guestNames.replace(' ', ','))
number += 1
guestList.sort()
# the with keyword will close the guestFile at the end
with open("guestList.csv","w") as guestFile:
guestFile.write('your headers\n')
for entries in guestList:
guestFile.write('%s\n' % entries)
Be aware that there are many ways to fulfil your demands, with different logics and methodologies.
Am trying to create a quiz program in Python where the questions are stored in one txt file with the answers in another. The questions are set out in the text file as follows:
Which one of these is a percussion instrument?
A. Trumpet
B. Euphonium
C. Viola
D. Glockenspiel
The program pulls the questions out in random order and keeps score of the number of right answers.
I know how to open files, read from them and display the contents of the file on the screen, I even know now how to randomise the info in the file. However, as there are multiple lines involved AND another file to get the answer from, I have no idea where to start.
I would really appreciate any help you could offer me.
Feel free to ask questions if you need to clarify anything.
EDIT:
Ok, I have decided to change my idea a little, which might make it easier. Using a CSV file might be the better option. Here is what I have so far.
def Trivia():
score=0
myFile = open("farming.csv","r") # opens the CSV file and stores it in the array myFile
players = myFile.readlines() # reads the lines of the CSV file into the variable players
questionno=1
while questionno < 6:
for p in players:
data = p.split(",") #splits each cell of the CSV file into its parts
questions = data[0]
answera = data[1]
answerb = data[2]
answerc = data[3]
CorrectAnswer = data[4]
print("Question #",questionno)
print(questions) #prints the question and the 3 answers
time.sleep(0.5)
print(answera)
time.sleep(0.5)
print(answerb)
time.sleep(0.5)
print(answerc)
time.sleep(0.5)
answer = input("Answer? ") #asks the user for their answer
time.sleep(1)
print(".")
time.sleep(1)
print(".")
time.sleep(1)
print(".")
if answer == CorrectAnswer: #checks if the answer is correct and prints approptiate responses
print("That is the correct answer")
score=score+1
time.sleep(1)
else:
print("That is not the correct answer")
time.sleep(1)
print("Your current score is", score)
print("")
questionno = questionno+1
myFile.close()
My problem now is that I don't know how to get to the next question in the quiz. Using this format it keeps asking the same question. Any idea?
Thanks.
This question is two-fold: what to save, and how to save. Let's answer "how" first.
Seems like what you need is serialization, which is a fancy way of saying "saving data in a particular format". I would learn about pickle or json. This will allow you to save and load objects, so you could for instance save a class that represents a question.
And about what you save and not how you save it, I guess each answer should be saved along with a number of a question, then you can link between them - sort of like foreign keys in a DB.
Good luck!
I am not exactly 100 percent sure as yet I haven't run the program myself to check. But I think it could be the "While" module. It says while questionno is under six, do that question, and so when you add 1 to questionno it is still under 6 running the program over again. Change it too this
If questionno == 1:
.....
.....
.....
for next question in the quiz you'll need to just start it with
If questionno == 2:
.....
.....
.....
now write the 2nd quiz
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