Home > Back-end >  how to convert bash script "switch case" to Python Switch Case
how to convert bash script "switch case" to Python Switch Case

Time:07-15

HI I need to change bash script "switch case" to Python Switch Case

my bash case is:

    read class
case $class in
    1)
            type="Samurai"
            hp=10
            attack=11
            magic=12
            ;;
    2)
            type="Warrior"
            hp=13
            attack=4
            magic=12
            ;;
    3)
            type="Ninja"
            hp=30
            attack=4
            magic=16
            ;;
esac
echo "You chosen the $type class. Your HP is $hp and your attack is $attack and your magic is $magic."

I try more things in python but can't do it Note: i using python3.

CodePudding user response:

It will be something like this. For python version 3.10 we have match case. But if you are using version before 3.10, and maybe you may not update py version for such small task. So here is Solution. Rather than using case, use "if".

varClass = "your class"
if varClass == 1:
    type = "Samurai"
    hp = 10
    attack = 11
    magic = 12
elif varClass = 2:
    type = "Warrior"
    hp = 13
    attack = 4
    magic = 12
elif varClass = 3:
    type="Ninja"
    hp=30
    attack=4
    magic=16
        

Hope This clears your answer. if you are using 3.10, then https://stackoverflow.com/users/3282436/0x5453, shared this which can work Replacements for switch statement in Python? well.

CodePudding user response:

You can use a list to hold the values

#! /usr/bin/env python3

class_ = int(input('?:'))

l = [
    {'type': 'Samurai', 'hp': 10, 'attack': 11, 'magic': 12},
    {'type': 'Warrior', 'hp': 13, 'attack': 4, 'magic': 12},
    {'type': 'Ninja', 'hp': 30, 'attack': 4, 'magic': 16}
]

c = l[class_]
print(
    f"You chosen the {c['type']} class. Your HP is {c['hp']} and your attack is {c['attack']} and your magic is {c['magic']}.")

and then you would be able to extend it easily just by adding elements.

  • Related