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...")
Related
I recently started working on my discord bot in python, and I made a "guess the character based on picture" game. I created a list of pictures of characters, but I want to make:
link on picture = character name
But I am totally lost, I didnt find any help on google.
Links = ["https://cdn.myanimelist.net/images/characters/7/299404.jpg", "https://cdn.myanimelist.net/images/characters/12/299406.jpg"]
Here's how you could do it with just lists:
Links = ["https://cdn.myanimelist.net/images/characters/7/299404.jpg",
"https://cdn.myanimelist.net/images/characters/12/299406.jpg"]
Chars = ["Izuku Midoriya", "Katsuki Bakugo"]
Guess the character?
Now if you show Links[0] the corresponding character will be Chars[0]
Although, a much better way and more appropriate way would be to use dictionaries.
mydict = {"Izuku Midoriya" : "https://cdn.myanimelist.net/images/characters/7/299404.jpg",
"Katsuki Bakugo" : "https://cdn.myanimelist.net/images/characters/12/299406.jpg" }
for character, link in mydict.items():
# show the picture from the link
# <put your code on how you want to show your link>
# receive the guess from user
guess = input('Enter your guess: ')
if guess.lower() == character.lower():
print('You guessed the right character!')
I have a code that allows me to identify keywords inputted from a user and the system displays the problem the keyword linked to and asks if it is correct. If the user inputs yes a solution is given
# The following is a database of problems, keywords, and solutions.
PROBLEMS = (('My phone does not turn on.',
{'power', 'turn', 'on', 'off'},
('put it on charger.',))
# These are possible answers accepted for yes/no style questions.
POSITIVE = tuple(map(str.casefold, ('yes', 'true', 'correct')))
NEGATIVE = tuple(map(str.casefold, ('no', 'false', 'incorrect')))
def main():
"""Find out what problem is being experienced and provide a solution."""
description = input('Welcome to the repair centre. Please state the problem with your device: ')
words = {''.join(filter(str.isalpha, word))
for word in description.lower().split()}
for problem, keywords, steps in PROBLEMS:
if words & keywords:
print('This may be what you are experiencing:')
print(problem)
if get_response('Does this match your problem? '):
print('Please follow the solution given')
for number, step in enumerate(steps, 1):
print('{}. {}'.format(number, step))
print('Once you have carried out the solution suggested by the system the problem with your device should be fixed .')
print('If you have carried out the solution suggested by the system and the problem is not fixed, please take the device to either the manufacturer or to the repair shop to get it fixed professionally.')
break
else:
print('Unfortunately the repair centre cannot help you with your problem.')
def get_response(query):
"""Ask the user yes/no style questions and return the results."""
while True:
answer = input(query).casefold()
if answer:
if any(option.startswith(answer) for option in POSITIVE):
return True
if any(option.startswith(answer) for option in NEGATIVE):
return False
print('Please respond with the positive or negative answer listed : yes, true, correct, no, false, incorrect.')
if __name__ == '__main__':
main()
However how can i store all the solutions in a text file and make the keywords stored in python link to it depending on the user input.
I want a specific line from the text file to be outputted to the user.
Help will be appreciated
We're going to store the keywords and solutions in a csv file. The first entry on each line will be the solution, and all the others will be keywords that direct to this solution.
from collections import defaultdict
import csv
sol_dict = defaultdict(set)
with open('solutions.csv', newline='') as f:
r = csv.reader(f, quotechar='|')
for solution, *keywords in r:
for keyword in keywords:
sol_dict['keyword'].add(solution)
So now we have this dictionary, sol_dict. We can query a keyword sol_dict['power'] and you get back a set of strings, each a solution. (When you make the csv, if you want commas in the solution, you can wrap it in the quotechar, |).
Then walking through the solutions would look something like
problem = input('What is your problem?')
for solution in set.union(*(sol_dict[word] for word in problem.split())):
# Whatever you want to do with solutions
print(solution)
name = ""
name = input("Hi there, what is your name? ")
while name.isalnum():
name = input("Hi there, what is your name? ")
while name.isdigit():
name = input("Hi there, what is your name? ")
This is what the code looks like, but I only want it to accept letters only. When I run this code however, there is a problem and the program keeps asking for the user's name for any input provided, the only way the program continues is if a 'space (bar)' is pressed. What is wrong with this?
while name.isalnum():
Means that the loop will keep running as long as name is alphanumeric. You want:
while not name.isalnum():
Your goal can be better achieved through regex:
import re
p=re.compile(r'[a-zA-Z\s]+$')
name="user0000"
while not p.match(name):
name = input("Hi there, what is your name? ")
This will accept names like "George Smith" but not "Smith1980"
Okay, so I am creating a program in python and basically it is a troubleshooting program for mobile phone users, it's very basic as of now, and I am in the situation where I am creating a list for the questions to be asked.
I will use the random module to randomise a string from the troubleshooting questions list, but I don't want it to randomise the first question in the list, then the first question in the list again.
So the real question; how do I check if the randomised string has already been randomised and if it has I want my program to randomise another string from the list, and if it has already been said then randomise another, if not use that string, etcetera.
Note: This program is no where near complete, I literally just started this now, so I am calling the function at the end so I can run the program at different times to see if it works.
import random
Questions = [
'Has your phone gotten wet?', 'Have you damaged your screen?', 'Is the phone at full battery?',
'Has your phone been dropped?', ' Does the mobile phone turn itself off?', 'Does the device keep crashing',
'Does the phone keep freezing?', 'Can you not access the internet on your phone?', 'Is the battery draining quickly?',
'Can you not access certain files on your phone?'
]
Solutions = [
'Put your mobile phone inside of a fridge, it sounds stupid but it should work!', 'Try turning your device on and off',
'Visit your local mobile phone store and seek help'
]
def PhoneTroubleshooting():
print('Hello, welcome to the troubleshooting help section for your mobile phone.\n'
'This troubleshooting program is going to ask you a series of questions, to determine the issue with your device.')
answer = print(random.choice(Questions))
if answer == 'yes':
print('Okay, I have a solution', random.choice(Solutions))
else: print('Okay, next problem')
PhoneTroubleshooting()
Instead of choosing a single random element at a time, you should randomize the entire list using shuffle, then iterate over that. i.e.
random.shuffle(Questions) # This shuffles `Questions` in-place
print(Questions[0])
...
Note, however, that you likely want to keep both of your lists coordinated -- i.e. you still want your answers to match your questions, so you should randomize the indices instead of the values:
inds = range(len(Questions))
random.shuffle(inds)
print(Questions[inds[0]])
...
print(Answers[inds[0]])
I apologize for my earlier questions as they were vague and difficult to answer. I am still fairly new to programming and am still learning the ins and outs of it all. So please bear with me. Now to the background information. I am using python 3.3.0. I have it loaded onto the Eclipse IDE and that is what I am using to write the code and test it in.
Now to the question: I am trying to learn how to create and use dictionaries. As such my assignment is to create a price matching code that through user interface will not only be able to search through a dictionary for the items (which are the keys and the locations and prices which are the values associated with the keys.) So far I have created a user interface that will run through well enough without any errors however (at least within the IDE) When I run through and input all of the prompts the empty dictionary is not updated and as such I cannot then make a call into the dictionary for the earlier input.
I have the code I have written so far below, and would like if someone could tell me if I am doing things correctly. And if there are any better ways of going about this. I am still learning so more detailed explanations around code jargon would be useful.
print("let's Price match")
decition = input("Are you adding to the price match list?")
if decition == "yes":
pricematchlist = {"Snapple":["Tops",99]}
location = input("Now tell me where you shopped")
item = input("Now what was the item")
price = input("Now how much was the item")
int(price)
pricematchlist[item]=location,price
print(pricematchlist)
else:
pricematchlist = {"Snapple":["Tops",99]}
reply = input("Ok so you want to search up a previous price?")
if reply == "yes":
search = input("What was the item?")
pricematchlist.item(search)
These are a few minor changes. For dictionaries: you are using them correctly.
print("let's Price match")
pricemathlist = {"Snapple":["Tops", 99]} # assign it here
decition = input("Are you adding to the price match list?").lower() #"Yes"-->"yes"
if decition == "yes":
# pricematchlist = {"Snapple":["Tops",99]}
# If this whole code block is called repeatedly, you don't want to reassign it
location = input("Now tell me where you shopped")
item = input("Now what was the item")
price = int(input("Now how much was the item"))
# int(price) does nothing with reassigning price
pricematchlist[item]=location,price
print(pricematchlist)
else:
reply = input("Ok so you want to search up a previous price?").lower()
if reply == "yes":
search = input("What was the item?")
print pricematchlist[search] # easier way of accessing a value