Search code examples
pythonpython-3.xif-statement

How to get different outputs from different inputs with an if statement in python?


So while trying to use an if statement and an input(), I ran into a slight (potentially skill related) issue: I was trying to do something were if I write 3 into x, the if statement outputs 3, if I write 15 it outputs 15. I want to do this within a singular if statement and not through 26 as I like code that's small and fast.

I have tried this bit of code

x = input()
if x = [1,2,3,4,...]
  [print(1),print(2),print(3),print(4)...]

and this one

x = input()

if x = [1,2,3,4,...]
  print([1,2,3,4,...]

but both failed to do what I wanted. I thought using lists would work but sadly, nope.


Solution

  • If you really just want to output whatever the user has input, as your question suggests, then you can just print the variable that you set the input to:

    x = input()
    print(x)
    

    This obviously doesn't do any input validation or anything, but provides the basic functionality that you were asking for.

    If you want to do something other than just print out the input, then you can use if and elif to do something different based on the input, for example:

    x = input()
    
    if x == "1":
       print("one")
    elif x == "2":
       print("two")
    elif x == "3":
       print("three")
    

    Also, for completeness, since Python 3.10 you can also use a Match Case statement, as follows:

    x = input()
    
    match x:
       case "1":
          print("one")
       case "2":
          print("two")
       case "3":
          print("three")
    

    The reason your code doesn't work is because you are checking if the variable x is equivalent to the list object [1, 2, 3, 4, ...], but x is a string containing the user input, and then even if x did equal that list object, you are then printing a representation of that whole list.