How Can I Put Keywords Into My Code? - python

Okay so how could I make my code so instead of putting 1 to 4 I could just put in a keyword like "Freezing" or "Froze" How could i put a keyword searcher in my code, all help is immensely appreciated thank you in advanced :)
def menu():
print("Welcome to Kierans Phone Troubleshooting program")
print("Please Enter your name")
name=input()
print("Thanks for using Kierans Phone Troubleshooting program "+name +"\n")
def start():
select = " "
print("Would you like to start this program? Please enter either y for yes or n for no")
select=input()
if select=="y":
troubleshooter()
elif select=="n":
quit
else:
print("Invalid please enter again")
def troubleshooter():
print("""Please choose the problem you are having with your phone (input 1-4):
1) My phone doesn't turn on
2) My phone is freezing
3) The screen is cracked
4) I dropped my phone in water\n""")
problemselect = int(input())
if problemselect ==1:
not_on()
elif problemselect ==2:
freezing()
elif problemselect ==3:
cracked()
elif problemselect ==4:
water()
start()
def not_on():
print("Have you plugged in the charger?")
answer = input()
if answer =="y":
print("Charge it with a diffrent charger in a diffrent phone socket. Does it work?")
else:
print("Plug it in and leave it for 20 mins, has it come on?")
answer = input()
if answer=="y":
print("Are there any more problems?")
else:
print("Restart the troubleshooter or take phone to a specialist\n")
answer=input()
if answer =="y":
print("Restart this program")
else:
print("Thank you for using my troubleshooting program!\n")
def freezing():
print("Charge it with a diffrent charger in a diffrent phone socket")
answer = input("Are there any more problems?")
if answer=="y":
print("Restart the troubleshooter or take phone to a specialist\n")
else:
print("Restart this program\n")
def cracked():
answer =input("Is your device responsive to touch?")
if answer=="y":
answer2 = input("Are there any more problems?")
else:
print("Take your phone to get the screen replaced")
if answer2=="y":
print("Restart the program or take phone to a specialist\n")
else:
print("Thank you for using my troubleshooting program!\n")
def water():
print("Do not charge it and take it to the nearest specialist\n")
menu()
while True:
start()
troubleshooter()

Since you want the user to type in the description of the phone's problem, you probably want a list of problems and keywords associated with those problems. The following program shows how you might arrange such a database and how to search it based on the user's input. There are faster alternatives to this solution (such as indexing the database), but this basic implementation should be sufficient for the time being. You will need to provide further code and information on how to resolve problems, but answers to your previous question should help direct you in that regard.
#! /usr/bin/env python3
# The following is a database of problem and keywords for those problems.
# Its format should be extended to take into account possible solutions.
PROBLEMS = (('My phone does not turn on.',
{'power', 'turn', 'on', 'off'}),
('My phone is freezing.',
{'freeze', 'freezing'}),
('The screen is cracked.',
{'cracked', 'crack', 'broke', 'broken', 'screen'}),
('I dropped my phone in water.',
{'water', 'drop', 'dropped'}))
# These are possible answers accepted for yes/no style questions.
POSITIVE = tuple(map(str.casefold, ('yes', 'true', '1')))
NEGATIVE = tuple(map(str.casefold, ('no', 'false', '0')))
def main():
"""Find out what problem is being experienced and provide a solution."""
description = input('Please describe the problem with your phone: ')
words = {''.join(filter(str.isalpha, word))
for word in description.lower().split()}
for problem, keywords in PROBLEMS:
if words & keywords:
print('This may be what you are experiencing:')
print(problem)
if get_response('Does this match your problem? '):
print('The solution to your problem is ...')
# Provide code that shows how to fix the problem.
break
else:
print('Sorry, but I cannot help you.')
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 provide a positive or negative answer.')
if __name__ == '__main__':
main()

You are looking for an enum
from enum import Enum
class Status(Enum):
NOT_ON = 1
FREEZING = 2
CRACKED = 3
WATER = 4
Then in your if checks, you do something like this:
if problemselect == Status.NOT_ON:
...
elif problemselect == Status.FREEZING:
...

Related

How do you stop a loop when a condition is met?

I'm a complete newbie to the coding trying my hands on python. While coding a simple program to calculate the age I ran into an error I cannot seem to fix no matter how hard I try. The code is pasted below. The program runs as far as I enter an year in the future, however when an year which has passed is used, the code loops again asking if the year is correct. Any help is appreciated.
from datetime import date
current_year = (date.today().year)
print('What is your age?')
myAge = input()
print('future_year?')
your_age_in_a_future_year= input()
future_age= int(myAge)+ (int(your_age_in_a_future_year)) - int(current_year)
def process ():
if future_age > 0:
print(future_age)
else:
print('do you really want to go back in time?, enter "yes" or "no"')
answer = input()
if answer =='yes':
print (future_age)
if answer == 'no':
print ('cya')
while answer != 'yes' or 'no':
print ('enter correct response')
process ()
process()
In this case, your function just needs to contain a while loop with an appropriate condition, and then there is no need to break out from it, or do a recursive call or anything.
def process():
if future_age > 0:
print(future_age)
else:
print('do you really want to go back in time?, enter "yes" or "no"')
answer = None
while answer not in ('yes', 'no'):
answer = input()
if answer == 'yes':
print(future_age)
elif answer == 'no':
print('cya')
try
...
if future_age > 0:
print(future_age)
return
else:
print('do you really want to go back in time?, enter "yes" or "no"')
...

After the first phone() why doesn't the it work?

print("what type of device do you have phone, tablet or laptop(put brackets at the end of your answer)?")
answer = input ("press enter and type in your answer. phone(), tablet() or console()")
def phone():
import webbrowser
print("Do you have an iphone or samsung?")
answer = input ('iphone/samsung:')
if answer == "iphone":
print("what type of iphone?")
answer = input ('5, 6 or 7:')
if answer == "samsung":
print("what type of samsung do you have?")
answer = input ('s5, s6 or s7:')
Indent block, be more careful!
def phone():
import webbrowser
print("Do you have an iphone or samsung?")
answer = input ('iphone/samsung:')
if answer == "iphone":
print("what type of iphone?")
answer = input ('5, 6 or 7:')
if answer == "samsung":
print("what type of samsung do you have?")
answer = input ('s5, s6 or s7:')
x = input("press enter and type in your answer. phone(), tablet() or console() ")
if x == 'phone()':
phone()
elif x == 'tablet()':
tablet()
elif x == 'console()':
console()
Essentially, what you have is this...
def foo():
print("stuff")
answer = input("type foo()")
And answer == "foo()" is True.
You never called foo(), though, you just typed it in as a string.
You need to run it.
exec(answer)
But, exec is really bad, so instead, you should instead use if and elif's to call the corresponding function.
if answer == 'foo()':
foo()

How to have if and elif in functions

First off. My code:
UserInput = ("null") #Changes later
def ask_module(param, param2):
elif UserInput == (param):
print(param2)
while True:
UserInput = input()
UserInput = UserInput.lower()
print()
if UserInput == ("test"):
print("test indeed")
ask_module("test2", "test 2")
I am not that good at coding, so this is probably something that I have done really wrong
This post seems a bit duchy, since I almost just have code,
but I have absolutely no idea on how to make this work.
What the code looks like without shortening:
while True:
UserInput = input()
UserInput = UserInput.lower()
print()
if UserInput == ("inventory"):
print("You have %s bobby pin/s" %bobby_pin)
print("You have %s screwdriver/s" %screwdriver)
elif UserInput == ("look at sink"):
print("The sink is old, dirty and rusty. Its pipe has a bobby pin connected")
else:
print("Did not understand that")
EDIT: I see that it might be hard to see what I'm asking.
I'm wondering how I can shorten my original code
If all your elif blocks have the same pattern, you can take advantage of this.
You can create a dictionary for the text you want to print and then do away with the conditionals.When it comes to choosing which one to print, you simply fetch the relevant text using its corresponding key. You use the get(key, default) method. If there is no key in the dictionary, the default value will be returned. For example,
choices = {'kick': 'Oh my god, why did you do that?',
'light him on fire': 'Please stop.',
'chainsaw to the ribs': 'I will print the number %d',
}
user_input = input().lower()
# individually deal with any strings that require formatting
# and pass everything else straight to the print command
if user_input == 'chainsaw to the ribs':
print(choices[user_input] % 5)
else:
print(choices.get(user_input, 'Did not understand that.'))
I found a solution, just stop using elif entirely.
Example:
userInput = "null"
def ask_question(input, output):
if userInput == (input):
print(output)
else: pass
while True:
userInput = input()
ask_question("test","test")
ask_question("test2", "test2")
ask_question("test3", "test3")

Make python remember what player picks and changes game depending on answer

the question i have sounds complicated but i'm sure its simple. i want my code to remember if the player is male or female and take them down different paths. so males have one story and females have another.
while True:
sex = raw_input ("> ")
if sex.lower() not in ('male', 'female'):
print("What? Try again")
continue
else:
break
if sex.lower() == "male":
print("'Okay Mr %s get ready for the test, it won't be easy'")% name
elif sex.lower() == "female":
print("'Well Ms %s i hope youre ready for the test'")% name
def male_questions():
# all the questions for men
def female_questions():
# all the questions for women
while True:
sex = raw_input ("> ")
if sex.lower() not in ('male', 'female'):
print("What? Try again")
continue
else:
break
if sex.lower() == "male":
print("'Okay Mr %s get ready for the test, it won't be easy'")% name
male_questions()
elif sex.lower() == "female":
print("'Well Ms %s i hope youre ready for the test'")% name
female_questions()
Note that this is a poor implementation of a finite state machine. The link may be able to help you build a much (MUCH) better one.
Also possible (without a state machine) if all you need to do is vary the question:
class Question(object):
def __init__(self, male_q, female_q):
"""Question("Do you have a beard? ", "Purses or wallets? ")"""
self.male = male_q
self.female = female_q
questions = [Question("foo","bar"), Questions("spam","eggs"), ...]
for num,question in enumerate(questions, 1):
print("{}. {}".format(num, question.__dict__.get(sex, "male")))

How do I change a sum for string for it to work?

This is my whole program I'm working on (with the function not in the right place due to the code needing to be indented) but anyway there is a problem that I'm not sure how to fix.
How do I change it so that this would work along with my program? It says that it is in a string but am not sure how to change this so it calculates the variables from the rest of my program. I am sorry seeming how this is not the only problem I am new to this and am just getting used to how this works.
import time
import random
def welcome():
ready="no"
while ready=="no":
print("Welcome To Encounter Simulator Inc. Where We Provide You with combat..")
print("Readying Start Up Sequence....")
time.sleep(0.5)
print("Welcome Are You Ready? Yes or No")
ready=input(str())
while ready!="yes" and ready!="no":
print("Yes or No Please")
ready=input(str())
def name():
areyousure="no"
while areyousure!="yes":
print("What do you want your 1st character to be named?")
name=input()
print("Are You Sure?(yes or no)")
areyousure=input(str())
if areyousure!="yes" and areyousure!="no":
print("Yes or No Please")
areyousure=input(str())
return name
def name2():
areyousure2="no"
while areyousure2!="yes":
print("What do you want your 2nd character to be named?")
name2=input()
print("Are You Sure?(yes or no)")
areyousure2=input(str())
if areyousure2!="yes" and areyousure2!="no":
print("Yes or No Please")
areyousure2=input(str())
return name2
def inputtingfor1(name):
areyousure3="no"
while areyousure3!="yes":
print("Please Input",name,"'s Attributes..")
skill1=input("The Skill Attribute= ")
strength1=input("The Strength Attribute= ")
print("Are You Sure? (Yes or No)")
areyousure3=input(str())
return skill1,strength1
def inputtingfor2(name2):
areyousure4="no"
while areyousure4!="yes":
print("Please Input",name2,"'s Attributes..")
skill2=input("The Skill Attribute= ")
strength2=input("The Strength Attribute= ")
print("Are You Sure (Yes or No)")
areyousure4=input(str())
return skill2,strength2
def difference1(skill1,skill2):
if skill1 >= skill2:
result0=skill1-skill2
result1=result0/5
elif skill1==skill2:
print("There Will Be No Skill Modifier")
result1=0
else:
result0=skill2-skill1
result1=result0/5
return result1
def difference2(strength1,strength2):
if strength1 >= strength2:
result10=strength1-strength2
result2=result10/5
elif strength1==strength52:
print("There Will Be No Strength Modifier")
result2=0
else:
result10=strength2-strength1
result2=result10/5
return result2
def dicerolling1():
print()
time.sleep(1)
print("This Will Determin Who Gets The Modifiers And Who Loses Them..")
dicenumber1=random.randint(1,6)
print(" The Dice Is Rolling For",name1,)
time.sleep(1)
print("And The Number",name1,"Got Was...",dicenumber1,)
return dicenumber1
def dicerolling2():
print()
time.sleep(1)
print("This Will Determin Who Gets The Modifiers And Who Loses Them..")
dicenumber2=random.randint(1,6)
print(" The Dice Is Rolling For",name2,)
time.sleep(1)
print("And The Number",name2,"Got Was...",dicenumber2,)
return dicenumber2
welcome()
name=name()
name2=name2()
skill1,strength1=inputtingfor1(name)
skill2,strength2=inputtingfor2(name2)
difference1(skill1,skill2)
difference2(strength1,strength2)
dicenumber1=dicerolling1()
dicenumber2=dicerolling2()
From the comment thread on the original question, the issue is that skill1 and skill2 are strings, which do not support the - operand. You need to cast them to ints before you perform any mathematical operation on them:
def difference1(skill1,skill2):
try:
s1 = int(skill1)
s2 = int(skill2)
except exceptions.ValueError:
print("Could not cast to int")
return None
if s1 >= s2:
result0 = s1-s2
result1=result0/5
elif s1==s2:
print("There Will Be No Skill Modifier")
result1 = 0
else:
result0=s2-s1
result1=result0/5
return result1
Depending on what you pass into difference1, you may not be left with an integer. If skill1 and skill2 could be parsed as floats, you'll hit an exception when you try to cast them to ints. If you know this will never be the case, you can remove the try-except block.
When skill1==skill2, result1 is not defined.
fix:
elif skill1==skill2:
print("There Will Be No Skill Modifier")
return 0

Categories

Resources