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")
Top comments (5)
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.
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
@vebss
good question!!
I'm still learning...but I like using dictionaries for instances like this. Maybe something like:
There are probably better ways, but this works for me. :)
@Brandon thanks, for this tip! :))