Im using a dictionary in my code and comparing the user's input to it, but when the user input nothing and just hits enter the program falls over and gives me a key error. I tried to use 'Try and Except' but that way the the program loops to the beginning which i dont want, i want to keep the program in the sub loop until the user inputs something that is within the boundary.
ftablet=open("tablet.txt").readlines() devicelist=["phone","tablet"]
dtablet = {}
for line in ftablet:
(key,val) = line.split(":")
dtablet[str(key)] = val.strip(",")
while True:
counter=0
device=""
while device not in (devicelist):
device=input(What is your device?: ").lower().replace(" ","")
print()
if device == "tablet":
usermodel=""
while usermodel != (dtablet["phonemodels"]):
print(dtablet["modelquestion"])
usermodel=input("Enter MODEL Here: ").lower().replace(" ","")
if usermodel in (dtablet["phonemodels"]):
name=""
while name != (dtablet[usermodel]):
print(dtablet["namequestion"])
print("Enter any of these : ",(dtablet[model]))
name=input("Enter NAME Here: ").upper().replace(" ","")
if name in (dtablet[usermodel]):
storage=""
while storage != (dtablet[name]):
print(dtablet["storagequestion"])
print("Enter any of these : ",(dtablet[name]))
storage=input("Enter STORAGE Here: ").upper().replace(" ","")
if storage in (dtablet[name]):
problem=input("What is the PROBLEM with your tablet?\nEnter Here: ").upper()
print()
for word in problem.split():
if word in (dtablet[storage]):
print(dtablet[word])
print("Thanks for using my troubleshooting program")
counter=1
if counter==0:
print("We dont have your keyword in out database")
else:
print("Sorry! We do not have that device in out database please choose from the ones listed above.")
This is My Text file that i converted into a dictionary which is called 'dtablet'.
modelquestion:What is the Model of your Tablet?
namequestion:What is the Name of your Tablet?
storagequestion:What is the STORAGE of your Tablet?
problemquestion:What is the PROBLEM with your Tablet?
phonemodels:apple,samsung,sony
apple:IPAD1,IPAD2,IPAD3
samsung:TAB1,TAB2,TAB3
sony:XPERIAZ2,XPERIAZ3,XPERIAZ4
IPAD1:16GB,32GB,64GB
IPAD2:16GB,32GB,64GB
IPAD3:16GB,32GB,64GB
TAB1:16GB,32GB,64GB
TAB2:16GB,32GB,64GB
TAB3:16GB,32GB,64GB
XPERIAZ1:16GB,32GB,64GB
XPERIAZ2:16GB,32GB,64GB
XPERIAZ3:16GB,32GB,64GB
16GB:cracked,broken
32GB:cracked,broken
64GB:cracked,broken
CRACKED:Problem = Cracked Solution = Take your phone to the repair
shop
BROKEN:Problem = Broken Solution = Take your phone to the repair shop
You have both
dtablet[model] # the key is the model variable
and
dtablet["model"] # the key is the "model" string
in your code, is this intentional?
If a user presses 'enter' then model will be an empty string, and this expression:
model in dtablet[model]
will always be true if dtablet[model] is a string.
Your issue is that you haven't included quotation marks around the key "model". This means that it wouldn't locate it anyway.
Also, why don't you just keep it to one loop? It'd be far more efficient.
First, you don't have a "model" key in your dictionary. You can print out dtablet.keys() and find if there is "model" in there. If not, then dtablet["model"] will 100% returns a KeyError.
Second, when you type while model != (dtablet["model"]):, since model is an empty string and if dtablet["model"] is a string then it will not go inside the while loop because an empty string is always a substring of any string.
You do realise that the while loop has both a break option and a continue option?
If you "want to keep the program in the sub loop until the user inputs something that is within the boundary" test and continue if the input was not what you were looking for.
Related
I have a little piece of code in Python where I'm trying to compare a user input to a specific element in an array. Here is the code:
movies = ["movie 1", "movie2", "movie3"];
answer = raw_input("What is your guess: ")
if answer == movies[1]
then print ("yes that is correct")
else:
print ("no that is incorrect")
I know the indentation above looks wrong becasue I typed it out in the text box and I'm new to this site as well as python.
I also know that I probably need to use some sort of conditional loop, maybe a while loop, but I'm having trouble finding where I can compare user input string value to a string value in my array. Any ideas how I might accomplish this?
Have fun with Python! I guess you are trying to make a loop which keeps receiving inputs from user to compare with the desired input until user types the correct input. If so, one way, it can be implemented as following (but think of adding a break condition, like input == "Bored" , to avoid infinite loop and hard stopping your code):
movies = ["movie 1", "movie2", "movie3"]
correctAnswer = movies[1]
is_notCorrect = True
while(is_notCorrect):
answer = raw_input("What is your guess: ")
if answer == correctAnswer:
print("Yes, that is correct")
is_notCorrect = False
else:
print("No, that is incorrect")
In the code above, when is_notCorrect turns into False. At next condition checking, it will break condition, and done with the loop.
Your code has some issues
movies = ["movie 1", "movie2", "movie3"]; # No need the semi-colon in Python
answer = raw_input("What is your guess: ")
# Need a colon here after if condition, new line, and indent.
#If you don't like the colon, you need to write a different way with one line of code Eg: <Do A> if <Condition happens> else <Do B>
if answer == movies[1]
then print ("yes that is correct") # No then in if-else statement in Python
else:
print ("no that is incorrect")
My question is about getting a user to pull and item from a list. If the item from the list isn't pulled from the list I want to tell the user that he is incorrect. So my code looks like this:
Body_Type = ['Large', 'Medium', 'Small']
print('Create a Character-')
print('Body Type Choices: ' + str(Body_Type))
bt = input('Enter your Body Type: ')
while bt != Body_Type:
if bt == Body_Type[0:]:
print('Your Body Type is: ' + bt)
else:
print('Invalid Body Type')
What I'm trying to do is make my user create a character. This is just the first part of my first simple project. I want to have him pull from one of the items on the list, being "Large, Medium, Small" respectively. I want it to repeat until the user chooses one of the three. I tried to use or but it seems to feel unorganized and I'd have to break up the list and assign each individual variable.
Thanks in advance!
Several errors here like comparing a string to a list, or random slicing hoping that it would work. And the fact that your input statement is before the loop creates an infinite loop because you're comparing 2 variables of a different type again and again (bt != Body_Type is always True regardless of the content of bt since left hand is a string, right hand is a list).
But it shouldn't be so complex to write some working code.
I would create an infinite loop and break only if choice is in the list:
while True:
bt = input('Enter your Body Type: ')
if bt in Body_Type:
print('Your Body Type is: ' + bt)
break
else:
print('Invalid Body Type')
simpler and clearer (and repeats input if fails). The infinite loop (with an always true condition) allows to avoid double input call & test. Just loop, input the string, and break from the loop if matches.
The key statement you were looking for was bt in Body_Type which tests if the string is within the list.
sorry, i'm not too sure how to phrase this question.
I am making a database of herbs to be used in cooking etc. and using a python scrip to search the database.
Basically i have multiple entries in the database that have the same name or similar (such as Siberian ginseng and panax ginseng). I would like to print out all of the entries that have the name in them (eg. ginseng), but am not sure how.
this is my code so far:
while True:
herb=input("Herb: ")
database=open("db.txt")
for line in database:
record = line.split('|')
if record[0] == herb:
found = True
break
else:
found = False
continue
if found == False:
print("No herbs in database.")
print('')
else:
print(record[0])
print(record[1])
print(record[2])
print(record[3])
print('')
The output only displays the first entry that has the herb (ginseng) in it, however i want all entries that have the name anywhere in it to be displayed.
Apologies if this question has already been answered or i haven't phrased it right.
It looks like your iterating over your records and when you find an entry that matches you break out of the loop and print it right away.
Something you might want to do is to make a printHerbs function which takes the record array and prints it when its found and not break the loop.
Also only display not found if they reach the end of the loop an nothing was found. It might look something like this:
herb=input("Herb: ")
database=open("db.txt")
def printHerbs(record):
print(record[0])
print(record[1])
print(record[2])
print(record[3])
print('')
found = False;
for line in database:
record = line.split('|')
if herb.lower() in record[0].lower():
found = True
printHerbs(record)
if found == False:
print("Herb not found in database")
Also if you are trying to match if a string is a substring of another string you can use:
if "Ginsing" in "Ginsing Tea":
print("Found")
The .lower() method will make sure both strings are lowercase when they are being compared.
I have a while statement which works well and I have a whole section of code that asks the user to input how many names they have which will then ask them for a name that amount of times and then each time a name will be entered.
I need the section of the names entered to be error tapped but I don't know how to do it, as I have a while statement and I may need to put another while statement in, although I have error tapped the section for amount of names in numbers.
Also there is code further on with a dictionary and sorts but I need help with the one section of error tapping started at while currentnum part
print("Please enter each name when asked without any spaces.") #The program will post this
print("Please enter each of your names individually also.") #Program will again post this
names = [] #This is the value of names which will be changed depending on the input
currentnum = 0 #Currentnum value is 0
while True: #While loop as it will revert to the start if question answered incorrectly
try:
numofnames = int(input("How many names do you have? "))
except ValueError: #if the input is not an integer or a whole number it will
print("Sorry that was not a valid input please retry")
continue #it will loop back and ask the question again as it says that the unput was not valid
else:
break #If the input is correct then the loop will break and continue to the next section of the program
while currentnum < numofnames: #This means that while currentnum is smaller than input for numofnames it will continue to ask question. This is another loop
currentnum = currentnum + 1 # every time the question is asked it means that currentnum gets 1 added to it and will continue to ask untill it is the same as the input for numofnames
name = str(input("Enter your name: ")) #Name asked to be entered in string
name = name.upper() #This changes all letters to upper case no matter what so there is no error for upper and lower case or a bigger dictionary showing lower and upper case values.
names.append(name)
Yep. The easiest way to describe what you're doing is to use the .isalpha attribute in an if statement. First you will have to def your while loop
Like the following:
def Loop():
name_input_complete = False
while name_input_complete != True:
string = input("Please input :")
string = str(string)
if string.isalpha():
name_input_complete = True
else:
print("Please do not use numbers and spaces")
Loop()
Loop()
Baisically you have to define the loop and then run it. The if statement(which is the part you should add to your loop) then checks if there is nothing other than letters. If true, your done with error trapping and the loop is exited. The program continues outside the loop. If not then the while is repeated because the Loop() function is called again.
Your code looks very good to me. I dont see what input can the user put that could cause an error, since most data in python can be stringed AND names can be pretty much anything!. If you could comment exactly what error could be caused i might be able to help you
Pretty new to python/programming in general, this is my biggest project yet.
I am writing a program that will do SUVAT equations for you. (SUVAT equations are used to find the displacement, start/end velocity, acceleration and time travelled by an object with constant velocity, you may call them something different.)
I made this list:
variables = ["Displacement", "Start Velocity", "End Velocity", "Acceleration", "Time"]
which is used in the following while/for loop:
a = 0
while a==0:
for variable in variables:
# choice1 is what the user is looking to calculate
choice1 = raw_input("Welcome to Mattin's SVUVAT Simulator! Choose the value you are trying to find. You can pick from " + str(variables))
# will execute the following code when the for loop reaches an item that matches the raw_input
if choice1 == variable:
print "You chave chosen", choice1
variables.remove(variable) #Removes the chosen variable from the list, so the new list can be used later on
a = 1 # Ends the for loop by making the while loop false
# This part is so that the error message will not show when the raw_input does not match with the 4 items in the list the user has not chosen
else:
if choice1 == "Displacement":
pass
elif choice1 == "Start Velocity":
pass
elif choice1 == "End Velocity":
pass
elif choice1 == "Acceleration":
pass
# This error message will show if the input did not match any item in the list
else:
print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks."
Hopefully the comments I have written in the code should explain my intentions, if not, feel free to ask anything.
The problem is that when I run the code, and input choice1, the for loop activates the last line of code:
else:
print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks."
and then prompts me to enter the input again, and will do this as many times as it needs to get to the item on the list that I am typing.
However, I specifically coded that if what I input does not match the item on the list the for loop is currently checking, but does match one of the other items on the list, then it should pass and loop round to checking the next item.
I am probably doing something stupid, but I don't see it, so please help me figure out what I have to do to get my desired result? I assumed it was the syntax I had wrong so that is why that is the title.
Thanks for any help, I appreciate it.
Besides the problem with the indentation in your pasted code, I would rewrite it as such:
while True:
choice = raw_input('...')
if choice in variables:
print "You chave chosen", choice
# Remove the chosen member from the list
variables = [v for v in variables if v != choice]
# Break out of loop
break
# Print error messages etc.
Also remember that string comparisons are case sensitive. I.e 'Displacement' != 'displacement'.