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()
Related
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
I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.
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).
I have a line in a function filter3 is a dict that I create via a shuffle function.
answer = shuffle(filter3)
print(answer)
userConfirm()
What I want to do is implement my userConfirm() function and if the user is unhappy with the output they select "N" and it will make answer go again.
Just not sure what to put in my "N" response in my function to make this happen.
import sys
def userConfirm():
"""get user confirmation to proceed"""
userChoice = raw_input("Are you happy with results? (Y or N or Q): ")
if userChoice == "N":
#What to do here
elif userChoice == "Q":
sys.exit("You Quit the Program")
elif userChoice == "Y":
print("OK Proceeding")
goto is considered harmful since the end of the sixties. Google for "goto considered harmful", there's an article by Dijkstra about that topic which became so famous that the phrase "considered harmful" nowadays is often reused for similar topics.
The reason is plain an simple: With goto you can create code which is hard to understand, hard to debug and hard to extend.
Use a proper loop for what you want. Rethink your problem from "I want to go back under this condition" to "I want to repeat this until this condition is met." Then writing it as a loop comes much easier and more natural.
Unfortunately, Python has no repeat … until for loops testing at the end. You only have for loops (for a specific list of iterations to perform) and while loops which test at the beginning, not the end. But you can use a while True for this and test explicitly in the end yourself:
while True:
do_something()
if break_condition:
break
Your second issue (given only in the comment below your question) can be solved by letting userConfirm() return a value stating whether the user wishes a repetition or not:
def userConfirm():
"""get user confirmation to proceed"""
userChoice = raw_input("Are you happy with results? (Y or N or Q): ")
if userChoice == "N":
return False
elif userChoice == "Q":
sys.exit("You Quit the Program")
elif userChoice == "Y":
print("OK Proceeding")
return True
while True:
do_something()
if userConfirm():
break
import sys
def userConfirm():
userChoice = raw_input("Are you happy with results? (Y or N or Q): ")
if userChoice == 'N':
return False
elif userChoice == 'Q':
sys.exit("You Quit the Program")
elif userChoice == 'Y':
print "OK Proceeding"
return True
while True:
answer = shuffle(filter3)
print answer
if userConfirm():
break
goto is always considered a bad programming practice after the advent of modern programming languages. It becomes hard to debug, track bugs/errors or even try to understand what in the hell you've written a few months ago(especially when your program deals with multiple nested if/else statements or loops). The best way to solve a problem without using goto is by structuring your program well. Grab a paper, design the structure. Now after you have a concrete plan with good logic, start coding. Use LOOPS, use BREAK and CONTINUE statements where necessary. These simple tricks/methods will help you build neat programs and save you from headaches. As they say "weeks of coding saves you hours of paperwork".
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".