Home > Back-end >  Is there a function in python that executes two different commands receiving different specific inpu
Is there a function in python that executes two different commands receiving different specific inpu

Time:11-15

I am quite new to programming so if this question is really silly please don't laugh at me :(

I am looking for a function to ask for (yes or no) questions, just like the below:

if input("Question (y/n)") == "y":
 print("y")
if input("Question (y/n)") == "n":
 print("n")

If the input equals "y" it would execute line 2, if it equals "n" it would execute line 4

I tried using two ifs, like above, however the input function would've been executed twice if I did it like that, I also tried using elif like below:

if input("Question (y/n)") == "y":
 print("y")
elif input("Question (y/n)") == "n":
 print("n")

But if I used the method shown above the input command would still be executed twice

I also tried this:

if input("Question (y/n)") == "y":
 print("y")
elif "n":
 print("n")

Doesn't work as everything other than "y" would execute line 4

Is there a function that can be used in such situation or is there a specific method to use "if" "elif" "else" to achieve such requirements? Much thanks! :))

CodePudding user response:

Is there a function that can be used in such situation or is there a specific method

Yes, the function is called input(). In fact, you almost have it correct. The one piece you are missing is that you need to store the result in a variable. Then you can reuse that result as many times as you wish without calling input() multiple times:

answer = input("Question (y/n)")

if answer == "y":
    # do something
elif answer == "n":
    # do something else
else:
    # print an error message

I suggest you read more about variables and how to use them to understand this.

CodePudding user response:

while True:
    x = input("y/n")
    if x == "y":
        #do suitable stuff 
        print(x)
    elif x == "n":
        #do suitable stuff
        print(x)
    else:
        #use "break" instead of "pass" if you want to get out the "while"
        pass 
  • Related