DEV Community

Cover image for Switch case, python?
Nati Thinks Tech
Nati Thinks Tech

Posted on

Switch case, python?

Ask your cat... "how can I use switch case in python?"
"- it's a conditional question, no?"
Yes! :)
maybe if you use the if, else or elif, you may see that this is possible.
Python doesn't use a "switch" in syntax so... you can use them in your code, exactly like this:

plants = int(input( "which seed do you want to buy?\n"
                      "1:Tulip"
                      "\n2:Rose bush"
                      "\n3:Pineapple"
                      "\n4:Banana\n"))
if plants == 1:
    print("Tulip" )
else:
    if plants == 2:
        print("Rose bush")
    else:
        if plants == 3:
            print( "Pineapple" )
        else:
            if plants == 4:
                print("Banana")
            else:
                if plants > 4:
                    print("enter a valid option")
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
gwutama profile image
Galuh Utama

I'm not a big fan of deeply nested blocks. It's just like you mentioned. I would use if elif else in python as replacement of switch.

if plants == 1:
  print("Tulip")
elif plants == 2:
  print("Rose bush")
elif plants == 3:
  print("Pineapple")
elif plants == 4:
  print("Banana")
else:
  print("enter a valid option")
Collapse
 
vebss profile image
vebss

Is there a reason to use if/else statements over using a dict? I didn't realize switch cases didn't exist in python and I'm curious which the general consensus for it's replacement is

Collapse
 
nati_thinks_tech profile image
Nati Thinks Tech

@vebss
good question!!

Collapse
 
phizzl3 profile image
Brandon

I'm still learning...but I like using dictionaries for instances like this. Maybe something like:

# Dictionary of {selections: values}
plants = {
    1: "Tulip",
    2: "Rose bush",
    3: "Pineapple",
    4: "Banana"
}
# Print options using loop and get selection from user
print("Which seed do you want to buy?")
for entry in plants:
    print(f'{entry}: {plants[entry]}')
selection = int(input("Selection: "))
# Print value from dictionary or message if not found
print(plants.get(selection, "Invalid option."))
Enter fullscreen mode Exit fullscreen mode

There are probably better ways, but this works for me. :)

Thread Thread
 
nati_thinks_tech profile image
Nati Thinks Tech

@Brandon thanks, for this tip! :))