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

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

Related

How do you call a variable that was returned at the end of a function?

I created this function and want to call the returned result but, I'm not sure how to get the variable back. If possible I'd also like a different message to pop up if the user types n. Could anyone help?
def give_entertainment():
random_form_of_entertainment = random.choice(form_of_entertainment)
good_user_input = "y"
while good_user_input == "y":
user_input = input(f"We have chosen {random_form_of_entertainment} for your entertainment! Sound good? y/n: ")
if good_user_input != user_input:
random_form_of_entertainment = random.choice(form_of_entertainment)
continue
else:
print("Awesome! Glad we got that figured out. Your trip is all planned! ")
return random_form_of_entertainment
x = give_entertainment()
Should store the return of your function into x.
With:
print(x)
you should see what's stored in your x variable.
Call the method while assigning it to a variable.
some_var = your_method()
Now this some_var variable have the returning value.
I'd personally use a recursive function for this, I made it work with y/n/invalid_input cases. Also with this an invalid input won't update random_form_of_entertainment so the user has to say y or n for it to change. I hope this is what you're looking for!
def give_entertainment():
random_form_of_entertainment = random.choice(forms_of_entertainment)
good_user_input = "y"
bad_user_input = "n"
invalid_input = True
while invalid_input:
user_input = input(f'We have chosen {random_form_of_entertainment} for your entertainment! Sound good? y/n: ')
if user_input == good_user_input:
print("Awesome! Glad we got that figured out. Your trip is all planned for!")
return random_form_of_entertainment
elif user_input == bad_user_input:
print("Sorry to hear that, let me try again...")
return give_entertainment()
else:
print("I don't recognize that input, please try again.")
continue
chosen_result = give_entertainment()
print(f'You chose {chosen_result}!')

I don't understand why my indentation is wrong, and when I input an answer it doesn't output anything, other than an error

I'm running this using PyScripter w/ Python 2.7.6. I don't understand why my code is wrong. Could someone give me an explanation?
def mainMenu():
answer = input("""Main Menu:
Pythagoras
Repeat Program
Quit""")
if answer == "Pythagoras":
pythagoras()
elif answer == "Repeat Program":
mainMenu()
elif answer == "Quit":
print("Program ended")
else:
mainMenu()
def pythagoras():
if answer == "Pythagoras":
aNotSquared = input("Input the value of A")
bNotSquared = input("Input the value of B")
aSquared = aNotSquared ** 2
bSquared = bNotSquared ** 2
valueC = aSquared + bSquared
print(valueC)
mainMenu()
Not sure if indentation errors occured when pasting over but outside that are a couple things to fix as well
Already test if answer == 'Pythagoras' before entering the pythagoras() function, doesn't work nor make sense to check answer inside the function
Cannot perform math on strings need to convert your input to int
General formatting for clarity, when taking inputs and printing result
PEP-8 snake_case not CamelCase
Slightly Improved Version:
from math import sqrt
def main_menu():
answer = input("""Main Menu:
Pythagoras
Repeat Program
Quit\nChoose option from above: """)
if answer == "Pythagoras":
pythagoras()
elif answer == "Repeat Program":
main_menu()
elif answer == "Quit":
print("Program ended")
else:
main_menu()
def pythagoras():
a_not_sqr = int(input("Input the value of A: "))
b_not_sqr = int(input("Input the value of B: "))
a_sqr = a_not_sqr ** 2
b_sqr = b_not_sqr ** 2
c_sqr = a_sqr + b_sqr
c_not_sqr = sqrt(c_sqr)
print(f'C Squared = {c_sqr}')
print(f'C = {round(c_not_sqr, 2)}')
main_menu()
Main Menu:
Pythagoras
Repeat Program
Quit
Choose option from above: Pythagoras
Input the value of A: 10
Input the value of B: 10
C Squared = 200
C = 14.14

Simple Quiz - How Do I Link Variables?

I'm stuck trying to figure out how to match the correct answer with the correct question. Right now if the user's answer is equal to any of the answers, it returns correct. Please help.
easy_question = "The capitol of West Virginia is __1__"
medium_question = "The device amplifies a signal is an __2__"
hard_question = "A program takes in __3__ and produces output."
easy_answer = "Charleston"
medium_answer = "amplifier"
hard_answer = "input"
questions_and_answers = {easy_question: easy_answer,
medium_question: medium_answer,
hard_question: hard_answer}
#print(easy_answer in [easy_question, easy_answer])
#print(questions_and_answers[0][1])
print('This is a quiz')
ready = input("Are you ready? Type Yes.")
while ready != "Yes":
ready = input("Type Yes.")
user_input = input("Choose a difficulty: Easy, Medium, or Hard")
def choose_difficulty(user_input):
if user_input == "Easy":
return easy_question
elif user_input == "Medium":
return medium_question
elif user_input == "Hard":
return hard_question
else:
print("Incorrect")
user_input = input("Type Easy, Medium, or Hard")
print(choose_difficulty(user_input))
answer = input("What is your answer?")
def check_answer(answer):
if answer == easy_answer:
return "Correct"
elif answer == medium_answer:
return "Correct"
elif answer == hard_answer:
return "Correct"
print(check_answer(answer))
You will want to keep track of the question:
question = choose_difficulty(user_input)
print(question)
answer = input("What is your answer?")
def check_answer(question, answer):
if questions_and_answers[question] == answer:
return "Correct"
return "Incorrect"
print(check_answer(question, answer))
There's a lot more cool stuff you can do, but this is a minimal example that should solve your problem!
EDIT:
When you did
questions_and_answers = {easy_question: easy_answer,
medium_question: medium_answer,
hard_question: hard_answer}
you created a dictionary (or dict as it's known in Python). See examples. Basically, you can do lookups by the first term (the question) and it'll return the second term (the answer).
The way I would do it: create 2 variables, x and y. If the users chooses "Easy", it sets x to 1, "Medium" sets it to 2 and so on. Then you ask him for an answer. The answer to the easy question, if correct, sets y to 1, on the medium to 2 and so on. Then you have a check if x == y. If yes, then he has answered correctly to the question.

How Can I Put Keywords Into My Code?

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:
...

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

Categories

Resources