My python code doesn't work - python

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()

Related

Pickle module that breaks the code from the book "Conceptual Programming with Python"

I'm taking the example from the book "Conceptual Programming with Python".
Some introduction to the problem that the code is aimed at solving:
Example: Creating a Knowledge Base
As a second example for OOP, we are going to implement a simple guessing game! But this game will be able to learn from experience, that is, you will be able to teach the program as you play. For this example, we will create a knowledge base of animals. The user will think of an animal, and the computer will have to figure out which animal it is by asking you (sensible) questions about that animal; the answer will be either yes or no. If it fails to guess correctly the animal, the program will ask you what would be a sensible question to be able to find the right solution next time!
Example 1: The computer only knows how to distinguish between a bird or a cat depending on whether it has 4 legs or not. That is, the initial knowledge base only contains these two animals and one single question.
You: Think of a cat.
Computer: Does it have 4 legs?
You: Yes
Computer: Were you thinking of a cat?
You: Yes
Computer: I knew it !! Let's keep playing! I am good at this!
Once again, this follows a tree structure! Depending on whether the user answers yes or no, the computer will ask a different question, or will provide an answer!
Example 2: You teach the computer a new question.
You: Think of a dog.
Computer: Does it have 4 legs?
You: Yes
Computer: Were you thinking of a cat?
You: No
Computer: What animal were you thinking of?
You: Dog
Computer: What is a question to distinguish between dog and cat?
You: Does it bark?
Computer: For a dog, what should be the answer?
You: Yes
Now for the pickle fragment:
Files need to be always opened first; then manipulate them (for example loading their content into a data structure), and finally close them when they are no longer in use. So, we are going to try to open a file called animal.kb in which we will save the tree. The first time we open the file, it will be empty, so we will create our previous knowledge base. To do so, we will use a try-except structure. Why? Whenever we try to open a file that doesn’t exist, this will create an exception FileNotFoundError. We can simply catch it and create the knowledge base ‘manually’. Then we let the user play, and we keep updating the knowledge base kb. At the end of the program, when the user doesn’t want to play anymore, we ‘dump’ the information contained in kb on the file “animal.kb”.
After the 2nd try with opening the "animal.kb" knowledge base the error appears:
```
Do you want to play? y
Traceback (most recent call last):
File "...\ConceptualPython02\knowledgeBase.py", line 71, in <module>
kb = kb.play()
AttributeError: 'NoneType' object has no attribute 'play'
Process finished with exit code 1
```
That's the problematic code:
import pickle
class Knowledge:
pass
class Question(Knowledge):
def __init__(self, text, if_yes, if_no):
self.text, self.if_yes, self.if_no = text, if_yes, if_no
def play(self):
if ask(self.text):
self.if_yes = self.if_yes.play()
else:
self.if_no = self.if_no.play()
return self
class Answer(Knowledge):
def __init__(self, text):
self.text = text
def play(self):
if ask("Were you thinking of a {} ? ".format(self.text)):
print("I knew it!")
return self
# here we got it right, # so we simply return the
# Answer node as it is.
else:
newanimal = input("What animal were\ "
"you thinking of? ")
newquestion = input("What is a question "
"to distinguish between {} and {} ?"
.format(self.text, newanimal))
# but in case we didn't know the animal
# we need to modify the node adding # the appropriate question and# what to do
# ifyes and if no
if ask("For {} , what should be the answer? ".format(newanimal)):
return Question(newquestion,
Answer(newanimal), self)
else:
return Question(newquestion,
self, Answer(newanimal))
def ask(q):
while True:
ans = input(q + " ")
if ans == "y":
return True
elif ans == "n":
return False
else:
print("Please answer y or n!")
try:
file = open("animal.kb", "rb")
kb = pickle.load(file)
file.close()
except FileNotFoundError:
kb = Question("Does it have 4 legs?", Question("Does it bark?",
Answer("dog"), Answer("cat")), Answer("bird"))
while True:
if not ask("Do you want to play?"):
break
kb = kb.play()
file = open("animal.kb", "wb")
pickle.dump(kb, file)
file.close()
Of course, also, it doesn't cache the new questions about the animals as it should have.
play should always return a Knowledge instance (or inherited from it). But when in Question.play the call to ask returns True, you don't return anything:
def play(self):
if ask(self.text):
self.if_yes = self.if_yes.play()
else:
self.if_no = self.if_no.play()
return self
So change the indentation of return self so it is always executed.

Why syntax error, code wont print in order

I wrote two different sequences, how do I get them to print in order? Do I need to use a loop? If so how would i do that?
name = input("Who Goes There?")
print("Ah" , name , "-I'll Call You Ted Instead")
water = input("Ted, Dont You Miss The Water?")
seagulls = input("What About The Seagulls?")
print(water, seagulls)
It's difficult to figure out what you're asking, particularly since there is no syntax error in that code. I'm assuming you're running it with the Python interpreter, yes(1)?
In any case, you only need a loop if you want to do things more than once. If all you want to do is execute some statements in sequence, you write them in the order desired, exactly as you have done, as the following transcript shows:
pax:~> python3 testprog.py
Who Goes There?pax
Ah pax -I'll Call You Ted Instead
Ted, Dont You Miss The Water?yes
What About The Seagulls?no
yes no
If the order of those actions is different to what you need, simply rearrange the statements into the order you do need.
(1) The reason I ask is that you do get a syntax error if, for example, you try to run it with a shell:
pax:~> bash testprog.py
testprog.py: line 1: syntax error near unexpected token `('
testprog.py: line 1: `name = input("Who Goes There?")'
But, if that's the case, you're just using the wrong tool to run it (possibly implicitly if it's executable and you just run it with ./testprog.py. You may benefit from the use of a shebang line to specify a different interpreter in that case, something like (the actual line may be different on your system but the concept is the same):
#!/usr/bin/env python3
name = input("Who Goes There?")
print("Ah" , name , "-I'll Call You Ted Instead")
water = input("Ted, Dont You Miss The Water?")
seagulls = input("What About The Seagulls?")
print(water, seagulls)
If you write a script - then run the entire script - the order should execute top-down.
name = input("Who Goes There?")
print("Ah" , name , "-I'll Call You Ted Instead")
water = input("Ted, Dont You Miss The Water?")
seagulls = input("What About The Seagulls?")
print(water, seagulls)
you can do this.
name = input("Who Goes There?")
print(f"Ah {name} I'll call you Ted Instead")
water = input("Ted, Dont You Miss The Water?")
seagulls = input("What About The Seagulls?")
print(water, seagulls)
or if you want you can do this too
name = input("Who Goes There?")
print("Ah {} I'll call you Ted Instead").format(name)
water = input("Ted, Dont You Miss The Water?")
seagulls = input("What About The Seagulls?")
print(water, seagulls)

Programming A Troubleshooting Program On Python [closed]

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

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 Will Not Launch External Applications Using os.system(<filepath here>)

Been using easygui in python to make gui boxes for various different system applications for windows over the past few days. What I want to know is, why doesn't my code work? It looks the same as the code that was working before? The program is a game launcher, and I shall be making one identical to this but working (with different, LAN compatible games) for people to select the game from the list. Looked on stack overflow and found somebody with a similar issue, however I don't believe his resolution would apply to my script. Will post code below,
thank you,
Matthew
import easygui as eg
import os
def menu():
msg="Please select a game:"
title="Select Game!"
choices=["Batman Arkham City", "Tomb Raider", "TESV Skyrim", "State of decay - Early Access", "Critical Strike Portable", "Terraria", "Doom", "Halo","Minecraft"]
reply=eg.buttonbox(msg,title,choices)
if choices=="Batman Arkham City":
batman()
elif choices=="Tomb Raider":
tomb()
elif choices=="TESV Skyrim":
skyrim()
elif choices=="State of decay - Early Access":
state()
elif choices=="Critical Strike Portable":
crs()
elif choices=="Terraria":
terr()
elif choices=="Doom":
doom()
elif choices=="Halo":
halo()
elif choices=="Minecraft":
minecraft()
def batman():
os.system('"C:\Program Files (x86)\Black_Box\Batman Arkham City\Binaries\Win32\BatmanAC.exe"')
menu()
def tomb():
os.system('"C:\Program Files (x86)\Tomb Raider\TombRaider.exe"')
menu()
def skyrim():
os.system('"C:\Program Files (x86)\The Elder Scrolls V Skyrim\SkyrimLauncher.exe"')
menu()
def state():
os.system('"C:\Games\State of Decay Early Access\StateOfDecay.exe"')
menu()
def crs():
os.system('"C:\Program Files (x86)\CS Portable\a.exe"')
menu()
def terr():
os.system('"C:\Games\Terraria\Terraria.exe"')
menu()
def doom():
os.system('"C:\DOOMWADS\doom.wad"')
menu()
def halo():
os.system('"C:\Program Files (x86)\Halo Combat Evolved\Halo.exe"')
menu()
def minecraft():
os.system('"C:\Games\minecraft.exe"')
menu()
menu()
Stack overflow has messed up my indents! Please assume these are correct as they are.
It's the backslashes that are causing the problem. Python interprets these itself, e.g. \n is a new line character.
Change them either to forward slashes, or to double backslashes.
os.system('"C:/DOOMWADS/doom.wad"')
I have fixed it.... Sorry for wasting anybodies time. The backslashes are fine because they are in '""', however in the menu section is "if choices=="game"" whereas it should be, "if reply=="game"". Thanks for the help! :)

Categories

Resources