2020-01-15 13:18:22

Hi all,
So I had started learning python in my school a few months ago. I have been creating a program for a compitition thiat is being held in our school. Given below is a part of the code with which I need help.
   print("How's the weather over there?")
   w=input()
   if(w=="hot"):
     print("Oh now I wish I wasn't  in this computer and could go out there and enjoy the heat!")
   elif(w=="rainy"):
     print("Wow! It's my favourite weather! I just can't resist the amazing atmosphere and the rainbow we see after the rain stops.")
   elif(w=="cloudy"):
     print("Doesn't it feel peaceful to just sit outside and watch the clouds? You should try it once.")
   elif(w=="cold"):
     print("You better have a warm blanket wrapped around your self and a cup of hot chocolate in your hands. This is the best solution for such a weather, according to my calculations.")
Now, what I want in this is that if I do not enter any of these things, it should show invalid input and then repeat the question and if I enter any of these words, it should show the result then move on to the next question. Can someone help me with this ASAP?

I am not someone who is ashamed of my past. I'm actually really proud. I know I made a lot of mistakes, but they, in turn, were my life lessons. Drew Barrymore
Follow me on Twitter, Discord and Instagram

2020-01-15 13:29:37

For invalid input, just attach an else statement on the end of your elif chain, IE:

elif(w=="cold"):
    ...
else:
    print("invalid")

For repeating, you can encapsulate your code in a while loop. Making it go through each question sequentially is a little more work, seeing as you'll have to keep track of which answers have been made or not. One simple way though could be to use a list to store words to check against, so something like:

words = []
if(w=="hot" and "hot" not in words):
    words.append("hot")
-BrushTone v1.3.3: Accessible Paint Tool
-AudiMesh3D v1.0.0: Accessible 3D Model Viewer

2020-01-15 16:18:41

@2, Yes I did put the invalid text in the else command but when I tried to put that entire thing in a while loop, it became an unending loop in which it did repeat the question again and again no matter if the answer is correct or wrong. I am not getting how to put this in a list. Could you perhaps explain it a little more?

I am not someone who is ashamed of my past. I'm actually really proud. I know I made a lot of mistakes, but they, in turn, were my life lessons. Drew Barrymore
Follow me on Twitter, Discord and Instagram

2020-01-15 18:15:52 (edited by amerikranian 2020-01-15 18:19:12)

Post 2's approach would work, but here is my solution.

def gather_user_input(question):
    """Gathers the user input to a given question. Will continue to repeat the question until the user types in anything.
    Parameters:
        question (str): The question which the user will be prompted to answer
    Return Value:
        User's response to the given question"""
    while 1:
        current_input = input(question)
        #Prevent the user from just hitting their enter key to move on
        if len(current_input) == 0: continue
        break
    return current_input
print(gather_user_input("Do you like bananas?"))
print(gather_user_input("How's the weather over there?"))

That is a simple version of what you want. The more advanced version is below, preventing the user from typing in something invalid

def gather_user_input(question, list_of_words):
    """Gathers the user input to a given question. Will continue to repeat the question until a valid word from the list is chosen.
    Parameters:
        question (str): The question which the user will be prompted to answer
        list_of_words (list): The valid responses to the question
    Return Value:
        User's response to the given question"""
    while 1:
        current_input = input(question)
        #Prevent the user from just hitting their enter key to move on
        if len(current_input) == 0: continue
        #Ensure that what the user typed in is a valid answer
        if current_input not in list_of_words: continue
        break
    return current_input
print(gather_user_input("Do you like bananas?", ["yes", "no"]))
print(gather_user_input("How's the weather over there?", ["Rainy", "Chilly", "Cool", "Cold", "Sunny"]))

I hope that this is helpful. You may wish to expand the script at some point to account for a valid answer that is typed using lowercase letters, but I'll leave it up to you. You may also wish to print the possible options a user can choose from if you end up using the second version of my script, but again, it's up to you as to how you implement it.

2020-01-15 18:51:38

Hi there,
first of all, you have a bug in the code.

   if(w=="hot"):
     print("Oh now I wish I wasn't  in this computer and could go out there and enjoy the heat!")

You see?... Hot weather is not enjoyable!!! big_smile

heh, just kidding, sorry for that. smile
Although I really hate temperatures above 25C, that's for sure.

Now, to the actual problem. There are few possible solutions, how to do it directly. But all of those I have currently on my mind deal quite messy with stopping the loop and returning value.
I would thus perhaps do it like this:

def get_response(question, *answers):
    while True: #Or a condition to end the input, if you want this functionality
        inp=input(question)
        if inp in answers:
            return inp
w=get_response("What is the weather there?", "hot", "rainy", "snow", "hail")
if w=="hot":
    print("Hmm, I would rather not be there, really.")
elif w=="snow":
#...

Of course this solution is primarily for an input system, where you have exact amount of predefined answers, and you need to get one of them.
It's not well suited for a chatbot system for example, where you will probably want to do some more tests on the string than just comparing against a predefined database of exact matches.
In that case, you can either write the while loops directly in the program and stop them in case of an  acceptable answer, or make a more complex system of phrases analysys, which would have a textual format describing possible kinds of comparisons, processing, etc.

Just for completeness, here is how an integrated while loop could look like:

w=""
while True:
    inp=input("What's the weather there?")
    if inp=="hot":
        print("Hmm, I would rather not be there.")
    else:
        print("Invalid input")
        continue

    w=inp
    break

In the end, w is empty if the user didn't specify anything, for example if there was an option to end the loop, or there is a value, if he entered a valid input.

Best regards

Rastislav

2020-01-15 20:51:43

@4 and 5, Thanks for your help. I was able to do it.
@5, I have a question. When you demonstrated the integrated while loop, I understood that you took w as a variable in which you wrote the loop. I have also understood that in the end, you have made w equal to inp and if that will happen the loop will break. What I don't understand is why you wrote continue along with the print command in which you wrote invalid input. Can you explain that?

I am not someone who is ashamed of my past. I'm actually really proud. I know I made a lot of mistakes, but they, in turn, were my life lessons. Drew Barrymore
Follow me on Twitter, Discord and Instagram

2020-01-15 21:07:15

Sure. continue is a command similar to break, with one exception, that instead of breaking the loop completely, it only stops its current iteration and moves it to the nextone. If I didn't use continue there, after the else statement, program would continue in the rest of the cycle's body and break it on the break command, returning even the invalid output. Thus I use continue to make the cycle go another round when it gets an invalid input, so it asks for another instead of proceeding further.

Best regards

Rastislav