I'm currently doing a beginners project on Python and got to a hurdle now, I need to insert an IF statement, I need a little help if anyone on here has experience in this please
Basically I want it to say "is there anything else I can help you with?"
This is where I keep getting an error, I want it to have a yes and no answer but not sure how to get them in. So if the user answers yes print what I put in and if they answer no then print another statement
There's a lot of ways to deal with this really, to get the yes or not answer you should prompt the user for an input initially which iirc can be done in Python by
Python:
input("Is there anything else I can help you with?")
However you want to save the response by the user so you can test it later to see if it's what you expected, this can be done using a variable and the assignment operator and then you can test its value in the IF statement.
This inherently will only run once, since the code will be executed line by line, so you may want to not let the user progress until they have given a response you expect, so a form of input validation. This can easily be achieved by using a loop, which tests the value the user inputs and if not as expected will restart the loop again. You could save the acceptable answers in an array, which a conditional (if) statement could check on each iteration of the loop to see if the response should be accepted
I get this is probably over complicating your request a bit, but it's the ex-tutor in me. I'll put a solution in a spoiler so you can have a look at what I mean, or try solve yourself
Python:
help = ""
answers = ['y','n']
while(True):
help = input("Is there anything else I can help you with? (y/n): ")
if(help not in answers):
continue
else:
break
An explanation of the above:
Create an initialised global variable help where we can save the response
Add some acceptable responses to an array so we can test input (could also add 'yes','no' or whatever)
use an endless while loop (sort of dangerous as this will run forever unless we break somewhere)
Get input from the user, save to the previously made variable
test the value returned by the user in an if/else conditional statement
if the entered value does not exist in the array, we continue (jump back to the top of the loop, re-ask the question) ((would probably be better to print an error, pointing to acceptable answers before asking again))
If it does exist (yay) then we break out of the while loop and the program finishes
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.