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.
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')
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 1 year ago.
Improve this question
I'm attempting to make an account creation software in which the user's 3 main details, their name, their random ID and password are all stored in a .txt document. The program runs fine however it can only store one array. Once I attempt to create a second account, it overwrites and deletes the first account. Is there any way to use json.dump() to write multiple arrays or do I need to use a different package?
def accCreation():
account = []
fullName = input("What is your full name?: ").upper()
print()
uniqueID = random.randint(100000, 999999)
print("Your unique, six digit ID, is:", uniqueID)
print("Write this down!. You will need it later!")
def passwordCreation():
print()
password = input("Please create a password: ")
account = [fullName, uniqueID, password]
with open('Cinema Login.txt', 'w') as login:
json.dump(account, login)
print("Account Created! Welcome!")
menu()
passwordCreation()
You're opening the file with the w flag which overwrites the file. To append to an existing file, use the a or a+ flag
with open('Cinema Login.txt', 'a') as login:
...
See this refernce page
You may want to read the Cinema Login file in full first, then update the accounts and write it all back:
def passwordCreation():
print()
password = input("Please create a password: ")
account = [fullName, uniqueID, password]
accounts = []
try:
with open('Cinema Login.txt', 'r') as login:
accounts = json.load(login)
except ValueError:
pass
accounts.append(account)
with open('Cinema Login.txt', 'w') as login:
json.dump(accounts, login)
print("Account Created! Welcome!")
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 2 years ago.
Improve this question
and I want to make a login system that uses this data to let the registered to be able to log in I tried to make one but couldn't, this is my registration coding
print("Enter your details here:\n")
student_name = input("Enter Your Username: ")
student_id = input("Enter Your ID: ")
student_email = input("Enter Your Email Address: ")
student_password = input("Enter Your Password: ")
f = open("students.txt", "a")
f.write("\n"+student_name+","+student_id+","+student_email+","+student_password)
f.close()
print("\n\t\t\t\tLoading...")
time.sleep(2)
name=input("You have finished your registration successfuly!! please press Enter to exit...:")
print("\n\t\t\t\tExiting...")
time.sleep(2)
exit()
Whenever storing a data in a file always use a dictionary or a list as these easily mutable.
Use any of the two given format to store the data
{'name':bot1,'std_Id':1234,'email':#mail,'pass':password}
[bot1,1234,#mail,password]
Now comes the main code:
f=open('students.txt','r')
stdId=input('StudentId: ')
pass=input('Password: ')
r=f.read()
#searching the file for the student ID and password
for match in r:
if r[1]==stdId: #use this if the data is stored in list
if r[3]==pass:
print('Login Successful')
else:
print('Incorrect Password')
else:
print('User not Found')
f.close
Explanation: Open the file in read mode and then store the data in a variable and then iterate through the file searching for the required data. Here I searched for the second index of the instantaneous data to match it with the given stdID.
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.