Programming A Troubleshooting Program On Python [closed] - python

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 6 years ago.
Improve this question
INCOMPLETE CODE
So one of my assignments is to create a troublshooting program that will indetify keywords within a query and link the user to a solution based on their input. Although this code works, any of the keywords will always call for the first solution... any ideas on how to correct this? Many thanks!
#CODE BEGINS
#damaged screen#
sol1 = ("If the battery of your mobile phone battery has swollen or changed appearance, we recommend removing the battery from the phone immediately and bringing them in store. This is something our technicians will have to look at.")
sol2 = ("We recommend bringing the phone in to a nearby store in able to gain help from a specialist.")
sol3 = ("We recommend factory resetting the phone or updating the mobile to the latest interface as the majority or errors are caused due to out-of-date interfaces.")
#subjected to damage#
sol4 = ("If the screen has been cracked, we recommend replacing the screen. If not, bring the phone into a store in order to seek help from a technician.")
sol5 = ("If the phone is water logged, we recommend removing the battery and allowing each piece of the phone to dry separately. Alternatively take the phone into a store.")
sol6 = ("We recommend taking the phone into a store, in order to seek help from a specialist.")
#editing#
sol7 = ("If you have recently changed the security settings on your phone there may be a corruption within your files. Please ensure you are entering your password correctly, and if this does not work, we recommend taking the phone into a store, in order to seek help from a specialist.")
sol8 = ("If you have recently deleted or edited files there may be a corruption within the files. In which case, please drop in to a nearby specialist in order to seek professional help.")
sol9 = ("If there has been a new update release for your device and many people are suffering a similar issue, there may be a manufacturing problem. We recommend taking the phone into a store, in order to seek help from a specialist.")
#file corruption#
sol10 = ("If you have recently attempted a factory reset and there has been an error you may need to retry this process. If the results come back the same, we recommend bringing the phone in to a nearby store in able to gain help from a specialist.")
sol11 = ("If there is a corruption within your files you may need to take your phone into a nearby store to gain professional help. This will ensure none of your files get lost in the process of storing them.")
sol12 =("We recommend factory resetting the phone or updating the mobile to the latest interface as the majority or errors are caused due to out-of-date interfaces.")
#corruptions due to download#
sol13 =("If you have recently download files from an external site there may be corruptions within the files or viruses. Please take your phone into a nearby store to gain professional help. This will ensure that no more damage is done to your device.")
sol14 =("If you have recently downloaded something from the app store your storage may be too full for your phone to run. In which case, please clear some space on your device.")
#If not solution can be provided, this outcome is the last message#
sol15 = ("Unfortunately we were not able to identify your problem. If you feel as though you may have made a mistake, you can restart this test. If there is no available solution we would recommend taking the phone into a store, in order to seek help from a specialist.")
import time
boolean = 0 #I have decided to use boolean operators in a way that they will act as subfunctions. This will help in directing the user to a specific solution instead of a general one.#
problemsolved = False
while problemsolved == False:
print("Hello, this system consists of multiple queries that will aim to help solve any problems that have arisen with your mobile device. If no solution is available the case number will be stored and revisited as soon as possible by a member of our customer support team.")
print("Let's get started, shall we?")
while boolean == 0:
problem1 = input("Is there something visably wrong with the phone?")
if problem1 == "yes":
print("Please describe in more detail.")
boolean += 1
elif problem1 == "no":
print("The problem is not to do with visable damage")
boolean+= 2
while boolean == 1:
problemexplainedone = str(input("Please decribe what is wrong with your phone."))
if ("battery" or "swollen" in problemexplainedone):
print(sol1)
elif ("screen" or "display" in problemexplainedone):
print(sol2)
elif ("error" or "message" in problemexplainedone):
print(sol3)
programfinished = input("Has the source of the problem been found and a solution suggested?")
if programfinished == "yes":
system = False
time.sleep(3)
exit()
elif programfinished == "no":
boolean += 1
while boolean == 2:
problem2 = input("Has the phone been subjected to damage?")
if problem2 == "yes":
print("Please describe in more detail.")
boolean += 1
elif problem1 == "no":
print("The problem is not to do with trauma to the hardware")
boolean+= 2
while boolean == 3:
problemexplainedtwo = str(input("Please decribe what is wrong with your phone."))
if ("battery" or "swollen" in problemexplainedtwo):
print(sol4)
elif ("screen" or "display" in problemexplainedtwo):
print(sol5)
elif ("error" or "message" in problemexplainedtwo):
print(sol6)
programfinished = input("Has the source of the problem been found and a solution suggested?")
if programfinished == "yes":
system = False
time.sleep(3)
exit()
elif programfinished == "no":
boolean += 1

You have to change occurences like
if ("battery" or "swollen" in problemexplainedone):
print(sol1)
to
if ("battery" in problemexplainedone or
"swollen" in problemexplainedone"):
Otherwise it always returns True, selecting the first solution.
The same for other if (... in ...) constructions.
Also some non-related tips:
Use an array for the solutions, that makes it easier to selecting a solution by index directly.
Do not use a variable named Boolean and assign it a number; give the variable a better name
use while not problemsolved instead of while problemsolved == False:
Use better casing, e.g. problemSolved

Related

Linking user input to a variable in a list

I got the task of creating code from a flow chart as follows.
You can see what it's asking me to do and as such, I think the method to doing this would be to assign the three languages to a separate variable each and then to assign "Welcome to ..." to its own variable as well.
However, I'm having problems with having the user input a link to one of the variables to print whatever is in that variable. Hopefully that makes sense, I'm new to this community and coding in general so I apologise for my issues. Thanks in advance!
On Stack Overflow, we don't normally write code, but here you go:
# Get user's selected language
userLanguage = input("What is your language? (English/French/Mandarin) ") # Ask the user the question
# Compare languages
if userLanguage.lower() == "english": # If the user entered "english", forced to lower-case by .lower()
print("Hello")
elif userLanguage.lower() == "french": # If the user entered "french"
print("Bonjour")
elif userLanguage.lower() == "mandarin": # If the user entered "madarin"
print("Ni Hao")
else: # The entered language was something else
print("Sorry, but I don't speak that")
# Welcome the user
print("Welcome to ...")
Adjust it to how you specifically need it, but there is a Python version of the flowchart.

python randomly shuffled multiple choice questionaire

I'm making a subclass for multiple choice questions under a superclass of trivia questions for my Python university course. The multiple choice aspect works, but I want to shuffle the order of the answers for extra credit.
Some of my code:
class ChoiceQuestion(Question) :
def __init__(self) :
super().__init__()
self._choices = []
def addChoice(self, choice, correct) :
self._choices.append(choice)
if correct :
# Convert len(choices) to string.
choiceString = str(len(self._choices))
self.setAnswer(choiceString)
# Override Question.display().
def display(self) :
# Display the question text.
super().display()
# Display the answer choices.
for i in range(len(self._choices)) :
choiceNumber = i + 1
print("%d: %s" % (choiceNumber, self._choices[i]))
The question choices are added in a seperate file I have no control over as a test-file. This is run by the professor after turning in whatever variation of the first code. Here is what he runs it on. Side note: there are of course import statements in the second file, but I have the other stuff solved and it's very long. Didn't want to include stuff that has been worked out.
print('\n')
mcq = ChoiceQuestion()
mcq.setText("In which country was the inventor of Python born?")
mcq.addChoice("Australia", False)
mcq.addChoice("Canada", False)
mcq.addChoice("Netherlands", True)
mcq.addChoice("United States", False)
for i in range(3) :
presentQuestion(mcq)
## Presents a question to the user and checks the response.
# #param q the question
#
def presentQuestion(q) :
q.display() # Uses dynamic method lookup.
response = input("Your answer: ")
if q.checkAnswer(response):
print("Correct")
else:
print("Incorrect") # checkAnswer uses dynamic method lookup.
# Start the program.
With that said, I need to display the options in a random order, while updating the number value tied to that choice slot. I.e. if Netherlands is randomized into slot 1, typing "1" will print "Correct". I also have to make sure I don't allow the same option to appear more than once.
How should I go about it? What are some suggestions? Note: I can only modify the first program
Here are a couple of things to think about:
As kiran.koduru mentioned, look at using the random module for easily shuffling lists.
Currently your code stores the correct answer as it is received. This makes it difficult because when the answers are shuffled the stored answer is no longer correct. An alternative is to store choice and correct together and calculate the correct answer after your choices are shuffled.
Your code does not know in addChoice whether or not there will be more choices added, so shuffling there will result in wasted computation.

My python code doesn't work

Struggling to work out why python complaining at line 4:
import sys
import re
problem = input("What is wrong with your mobile device?").lower
water = re.search(r'water', problem)
screen = re.search(r'screen', problem)+ re.search(r'smashed',problem)or re.search(r'cracked',problem)+ re.search(r'display',problem)
software=re.search(r'software',problem)+ re.search(r'program',problem)
keypad=re.search(r'keypad',problem)+ re.search(r'keyboard',problem)+ re.search(r'text',problem)
speakers=re.search(r'sound',problem)+ re.search(r"can't here",problem)+ re.search(r'cant hear',problem)
microphone=re.search(r'microphone',problem)+ re.search(r'cant hear me',problem)+ re.search(r"can't hear me",problem)
battery=re.search(r'battery',problem)+ re.search(r'swollen',problem)
charger=re.search(r'Charger',problem)+ re.search(r'charge',problem)+ re.search(r'charging',problem)
if water:
print("If your phone has suffered water dammage there is not much you can do, it is recomended that you buy a new phone")
sys.exit
elif screen:
print("If your screen is cracked then it is recomended that you get it repaired this is not too expensive.")
sys.exit
elif software:
print("If you have a software issue then contact the product manurfacture, they are the only ones qualified to fix this.")
sys.exit
elif keypad:
print("Clean your keypad with a wetwipe, do not get the charger port or jack port wet.")
sys.exit
elif microphone:
print("Your microphone hole may be blocked, please clean this with a soft dry tooth brush, if this does not work then please retern the hand held device to its manufactures.")
sys.exit
elif battery:
print("If your battery is enlarged/swollen you have probbaly over charged it it is recomended that you buy a ned battery.")
sys.exit
elif speakers:
print("The speaker on most phone is located on the side or back or the device if this is blocked then please attemt to clean this with a dry, soft toothbrush, if this does not work please contact the product manurfacture.")
sys.exit
elif charger:
print("If you have not tryed buying a new charger then try that. If a new charger does not work, please send your mobile device to the product manurfacture.")
sys.exit
else:
print("please write your problem again, attempt to use keywords that relate to your problem.")
sys.exit
If someone could tell me how to correct this or correct this themselves it would be much appreciated.
you are not calling the function lower in line 3. In order to call it, you have to write 2 parenthesis after it. Thus, correct that line as follows:
problem = input("What is wrong with your mobile device?").lower()
The problem is actually on line 3. According to this article, Python 2 uses raw_input to get input, while Python 3 uses input. It looks like your code is expecting a Python 3 environment, but your environment is actually Python 2.
You can replace your call to input with a call to raw_input if you are, indeed, running in a Python 2 environment.
In addition, you must use parentheses after the call to lower so that the method actually gets called.
Python 2
problem = raw_input("What is wrong with your mobile device?").lower()
Python 3
problem = input("What is wrong with your mobile device?").lower()

My python code runs a few times but as soon as I close my computer or do something else, it doesn't run again

Running this code a few times presents no issues. Upon attempting to show a friend, it doesn't work. It just hangs after the input. It's worked quite a few times before but never again unfortunately.
I've tried rewriting the code in brackets, rewriting the code to a local directory instead of the Google Drive folder I have and I've even tried rewriting from scratch in regular notepad. All this was tried in case some sort of encoding issue had occured. No such luck. I figure something is wrong with the interpreter but I'm not sure how to remedy the situation.
def bin2dec():
bin = []
a = int(input("What number are you converting to binary?: "))
while a > 0:
if a % 2 == 0:
bin.insert(0, 0)
a = a/2
elif a % 2 == 1:
bin.insert(0, 1)
a = a/2-0.5
else:
#repetition
print("Your binary equivalent is:", bin)
repeat = input("Would you like to convert another binary number?: ")
if repeat == "yes":
bin2dec()
bin2dec()
Oh....welp. It seems the problem was actually that I somehow installed two versions of pythons and I guess they had been interfering with each other. Reason I'm not deleting this Q is because I'm sure I'm not the only one who's made this mistake. However, others have probably made this mistake in an effort to ensure compatibility between versions. Bad idea.

Python autocomplete user input [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a list of teamnames. Let's say they are
teamnames=["Blackpool","Blackburn","Arsenal"]
In the program I ask the user which team he would like to do stuff with. I want python to autocomplete the user's input if it matches a team and print it.
So if the user writes "Bla" and presses enter, the team Blackburn should automatically be printed in that space and used in the rest of the code. So for example;
Your choice: Bla (User writes "Bla" and presses enter)
What it should look like
Your Choice: Blackburn (The program finishes the rest of the word)
teamnames=["Blackpool","Blackburn","Arsenal"]
user_input = raw_input("Your choice: ")
# You have to handle the case where 2 or more teams starts with the same string.
# For example the user input is 'B'. So you have to select between "Blackpool" and
# "Blackburn"
filtered_teams = filter(lambda x: x.startswith(user_input), teamnames)
if len(filtered_teams) > 1:
# Deal with more that one team.
print('There are more than one team starting with "{0}"'.format(user_input))
print('Select the team from choices: ')
for index, name in enumerate(filtered_teams):
print("{0}: {1}".format(index, name))
index = input("Enter choice number: ")
# You might want to handle IndexError exception here.
print('Selected team: {0}'.format(filtered_teams[index]))
else:
# Only one team found, so print that team.
print filtered_teams[0]
That depends on your usecase. If your program is commandline based, you can do that at least by using the readline module and pressing TAB. This link also provides some well explained examples on that since its Doug Hellmanns PyMOTW. If you are trying that via a GUI it depends on the API you are using. In that case you need to deliver some more details please.

Categories

Resources