I'm using the example below:
APT command line interface-like yes/no input?
I want to make it its own definition as outlined then call it upon demand, like this:
def log_manager():
question = "Do you wish to continue?"
choice = query_yes_no_quit(question, default="yes")
if choice == 'y':
print ("you entered y")
else:
print ("not working")
Regardless of what I input, "not working" is always printed. Any guidance would be really appreciated!
The function returns True/False. So use if choice:
Btw, you could have easily found out the solution on your own by adding print choice ;)
Use:
if choice:
print("you entered y")
else:
print("not working")
the function returns True / False, not "y" / "n".
Related
I'm trying to create a simple script that will will ask a question to which the user will input an answer (Or a prompt with selectable answers could appear?), and the program would output a response based on the input.
For example, if I were to say
prompt1=input('Can I make this stupid thing work?')
I would have something along the lines of
if prompt1='yes':
print('Hooray, I can!')
else prompt1='No':
print('Well I did anyway!')
elif prompt1=#an answer that wouldn't be yes or no
#repeat prompt1
I'm probably going about this the wrong way. Please be as descriptive as possible as this is a learning exercise for me. Thanks in advance!
You are pretty close. Read a good tutorial :)
#!python3
while True:
prompt1=input('Can I make this stupid thing work?').lower()
if prompt1 == 'yes':
print('Hooray, I can!')
elif prompt1 == 'no':
print('Well I did anyway!')
else:
print('Huh?') #an answer that wouldn't be yes or no
while True will loop the program forever.
Use == to test for equality.
Use .lower() to make it easier to test for answers regardless of case.
if/elif/elif/.../else is the correct sequence for testing.
Here's a Python 2 version:
#!python2
while True:
prompt1=raw_input('Can I make this stupid thing work?').lower()
if prompt1 == 'yes':
print 'Hooray, I can!'
elif prompt1 == 'no':
print 'Well I did anyway!'
else:
print 'Huh?' #an answer that wouldn't be yes or no
raw_input is used instead of input. input in Python 2 will tries to interpret the input as Python code.
print is a statement instead of a function. Don't use () with it.
Another example, this time as a function.
def prompt1():
answer = raw_input("Can I make this stupid thing work?").lower()
if answer == 'yes' or answer == 'y':
print "Hooray, I can!"
elif answer == 'no' or answer == 'n':
print "Well I did anyway!"
else:
print "You didn't pick yes or no, try again."
prompt1()
prompt1()
I've got written a calculator on python 3 in pycharm edu. The part of the code is here:
def again():
calc_again = input('''
Repeat?
''')
#disagreements = frozenset('N'or 'No' or 'Not')
#agreements = frozenset('Y' or 'Yes' or 'Ya')
if (calc_again.upper()=='Y' or calc_again.upper()=='Yes' or calc_again.upper()=='Ya'):
calc()
elif (calc_again=='N' or calc_again=="No" or calc_again=='Not'):
print('Exit')
again()
else:
print('Type y/n')
The problem appears when I'm trying to input any other condition except Y and N, it just doesn't respond fine, and I doubt it's case insensitive as well.
I was trying to use:
if calc_again.upper() in agreements:
do..
but it just gives me the same result.
Can somebody fix it and explain?
Also, may be it's better to use "while True" instead of "again()" (11 str)?
UPD
with last changes it looks like
def again():
possible_conditions = frozenset(['y', 'yes', 'ya', 'n', 'no', 'not'])
calc_again = input('Go again?')
agreements = frozenset(['y', 'yes', 'ya'])
if calc_again.lower() in possible_conditions:
if calc_again.lower() in agreements:
calc()
else:
print('bye')
exit()
else:
print('choose y or n')
again()
Your problem is that you are checking UPPER version of calc_again string. So you will have always uppercase letters in calc_again.upper(). To fix your code, just make your list of possible cases upper.
if (calc_again.upper()=='Y' or calc_again.upper()=='YES' or calc_again.upper()=='YA'):
calc()
elif (calc_again=='N' or calc_again=="NO" or calc_again=='NOT'):
print('Exit')
again()
else:
print('Type y/n')
Also, I think you have to put your if statements in while loop, because it have to be executed always depending on user inputs.
(py) At the moment, the code below does not validate/output error messages when the user inputs something other than the two choices "y" and "n" because it's in a while loop.
again2=input("Would you like to calculate another GTIN-8 code? Type 'y' for Yes and 'n' for No. ").lower() #**
while again2 == "y":
print("\nOK! Thanks for using this GTIN-8 calculator!\n\n")
restart2()
break #Break ends the while loop
restart2()
I'm struggling to think of ways that will allow me to respond with an output when they input neither of the choices given. For example:
if again2 != "y" or "n"
print("Not a valid choice, try again")
#Here would be a statement that sends the program back to the line labelled with a **
So, when the user's input is not equal to "y" or "n" the program would return to the initial statement and ask the user to input again. Any ideas that still supports an efficient code with as little lines as possible? Thanks!
def get_choice(prompt="Enter y/n?",choices=["Y","y","n","N"],error="Invalid choice"):
while True:
result = input(prompt)
if result in choices: return result
print(error)
is probably a nice generic way to approach this problem
result = get_choice("Enter A,B, or C:",choices=list("ABCabc"),error="Thats not A or B or C")
you could of coarse make it not case sensitive... or add other types of criteria (e.g. must be an integer between 26 and 88)
A recursive solution:
def get_input():
ans = input('Y/N? ') #Use raw_input in python2
if ans.lower() in ('y', 'n'):
return ans
else:
print('Please try again.')
return get_input()
If they're really stubborn this will fail when it reaches maximum recursion depth (~900 wrong answers)
I'm learning python and I found myself lost trying to create a an if statement that should be true if the user input y or yes.
#!/usr/bin/env python3
user_input = input('Would you like to go on?')
lowui = user_input.lower
if lowui == ('y' or 'yes'):
print('You want to go on')
else
print('See you later, bye')
The problem is that it becomes true only if I type y but not for yes. If I remove the parenthesis it becomes always false. Ok, I can do a workaround like
if lowui == 'y' or lowui == 'yes':
but I was wondering if there is any trick that don't force me to write so many times tha variable.
Thank you in advance.
Change it to
if lowui in ('y', 'yes'):
Also this is wrong:
lowui = user_input.lower
it should be:
lowui = user_input.lower() # Actually call the lower function
What I'm trying to do is that, if I ask a question only answerable by Yes and
No, I want to make sure that yes or no is the answer. Otherwise, it will stop.
print("Looks like it's your first time playing this game.")
time.sleep(1.500)
print("Would you like to install the data?")
answer = input(">").lower
if len(answer) > 1:
if answer == "no":
print("I see. You want to play portably. We will be using a password system.")
time.sleep(1.500)
print("Your progress will be encrypted into a long string. Make sure to remember it!")
else:
print("Didn't understand you.")
elif len(answer) > 2:
if word == "yes":
print("I see. Your progress will be saved. You can back it up when you need to.")
time.sleep(1.500)
else:
print("Didn't understand you.")
First:
answer = input(">").lower
should be
answer = input(">").lower()
Second, len(answer) > 1 is true for both "no" and "yes" (and anything larger than one character, for that matter). The elif block will never be evaluated. Without modifying significantly the logic of your current code, you should do instead:
if answer == 'no':
# do this
elif answer == 'yes':
# do that
else:
print("Didn't understand you.")
Something like:
if word.lower() in ('yes', 'no'):
would be the simplest approach (assuming case doesn't matter).
Side-note:
answer = input(">").lower
Is assigning a reference to the lower method to answer, not calling it. You need to add parens, answer = input(">").lower(). Also, if this is Python 2, you need to use raw_input, not input (In Python 3, input is correct).