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')
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 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')
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.
So, basically, this is my code:
import random
import os
answer = input('What is the problem with your mobile phone? Please do not enter more than one sentence.')
print('The program has detected that you have entered a query regarding: '
if 'wet' or 'water' or 'liquid' or 'mobile' in answer:
print('Put your mobile phone inside of a fridge, it sounds stupid but it should work!')
What I want to know is, say for example if the user enters the keywords 'wet' and 'mobile' as their input, how do I feed back to them knowing that my program has recognised their query.
So by saying something like 'The program has detected that you have entered a query regarding:' how do I filter their keywords into this sentence, say, if they entered 'My mobile phone has gotten wet recently', I want to pick out 'mobile' and 'wet' without saying:
print('The program has detected that you have entered wet')
Because that sounds stupid IMO.
Thanks
If I understand your question correctly, this should solve your problem. Just put the print statement inside the if condition! Very simple, I guess :)
import random
import os
answer = input('What is the problem with your mobile phone? Please do not enter more than one sentence.')
if 'wet' or 'water' or 'liquid' or 'mobile' in answer:
print('The program has detected that you have entered a query regarding: water') # or anything else wet or whatever
print('Put your mobile phone inside of a fridge, it sounds stupid but it should work!')
You can do that with a tuple, a list and any function:
SEND_REPORT_TUPLE = ('wet', 'water', 'liquid', 'mobile')
#make a list from the input
input_list = answer.split(" ")
#And then the use any function with comprehension list
if any(e in SEND_REPORT_TUPLE for e in input_list):
print("The program has detected a query...")
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
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.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
Hey Im having a problem with my while loop for adding values to dictionary
contacts = {}
addContact = 'yes'
while addContact == 'yes':
name1 = input('Please enter the name of the contact: ')
num = int(input('Please enter the phone number of the contact: '))
email1 = input('Please enter the email of the conact: ')
contacts[name1] = num, email1
addContact = input('Would you like to add another Contact? (yes or no): ')
if addContact == 'no':
break
print(contacts)
The loop will only add the values that were last input by user, how can I get it to add all values?
While using this in Python 2.7 and changing the inputs to raw_input I received the following output:
C:\Python27\Doc\Python Programs\Book>test.py
Please enter the name of the contact: test1
Please enter the phone number of the contact: 123456789
Please enter the email of the conact: test1#yahoo.com
Would you like to add another Contact? (yes or no): yes
Please enter the name of the contact: test2
Please enter the phone number of the contact: 234567891
Please enter the email of the conact: test2#yahoo.com
Would you like to add another Contact? (yes or no): no
{'test1': (123456789, 'test1#yahoo.com'), 'test2': (234567891, 'test2#yahoo.com')}
Using your exact code.
Your code is running fine. However if you are entering multiple values let's say a same name, number, or email. You are going to change the value. For example from my output, if I put in test1 as the name with the number 123456789 then entered another test1 with the number 987654321 it will replace the first one with the second one. You need to have a set of code to check for multiple inputs that are the same and then inputs them as a new contact rather than replacing the previous one.
I would try something along the lines of adding a function that scans to see if the input already exists in the dictionary contacts. If it does then add it to the dictionary in a different place.
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